我可以在使用正则表达式时让 python 将我的文件读取为 UTF-16 LE BOM 吗?

Can I make python read my file as UTF-16 LE BOM while using regex?

提问人:Sean McNally 提问时间:9/25/2021 更新时间:9/25/2021 访问量:271

问:

我正在尝试编写一段代码,该代码将从 Premiere Pro 导出的章节标记的文本文件转换为 ffmpeg 可读的格式。

问题是,它们以 Notepad++ 报告为 UTF-16 LE BOM 的文件的形式出现。如果我将其更改为 UTF-8 然后保存,我的代码将正常工作。但是,我想知道是否有更简单的方法来修改我的代码而不是转换每个 .txt 文件。

这是一个测试代码,只需将时间戳从 hh:mm:ss:ff 转换为毫秒并打印出来。同样,它适用于 UTF-8 文件:

import math
import re

with open('chapters.txt', 'r') as f:
   next(f)
   for line in f:
      x = re.match(r".*?\t\t\t(\d{2}):(\d{2}):(\d{2}):(\d{2})", line)
      hrs = int(x.group(1))
      mins = int(x.group(2))
      secs = int(x.group(3))
      frms = int(x.group(4))

      minutes = (hrs * 60) + mins
      seconds = secs + (minutes * 60)
      milliseconds = (seconds * 1000)
      frames = math.ceil(frms * 41.7)
      timestamp = (milliseconds + frames)
      print(timestamp)

以下是 Premiere Pro 中的文件的外观:

    Asset Name              In Point            Description 
    video           00:03:45:10                         
    video           00:12:26:19                         
    video           00:22:30:07                         
    video           00:34:42:22                         

免责声明:我不知道我在做什么。

python-3.x 正则表达式 UTF-16

评论

1赞 Matthias 9/25/2021
为什么在打开文件时不设置编码? 应该工作。with open('chapters.txt', 'r', encoding='utf-16') as f:
0赞 Sean McNally 9/25/2021
这就是答案!有时,最简单的解决方案是正确的。不知道如何将此评论标记为已验证的答案,但谢谢。

答: 暂无答案