python - 如何在 UTF-8 文件的开头去除垃圾字符
问题描述
我在 Python 3.9 中有以下代码并且它可以工作,除了我在 UTF-8 编码文本文件的开头得到一个垃圾字符,这使它错误地读取了第一行的第一个字符。如何去除我正在阅读的 UTF-8 文件开头的任何垃圾字符?
这是代码:
actions = {'#': 'comment', 'A': 'action', 'T': 'text for polly', 'F': 'filename'}
action = "#"
poly_text_received=False
script_line = "none"
line_cnt = 0
with open(input("Enter the script filename: "),'r') as script_file:
for line in script_file:
line_cnt = line_cnt + 1
line = line.strip()
action = actions.get(line[0])
if action == 'comment': #Action is a comment
line = line[1:].lstrip(':')
print(f'Ignoring comment: \n'
f' {line}')
这是输入文件的示例 - 代码还有更多内容,它总是查看行的第一个字符,并根据该字符执行特定操作:
#Preceed each comment with "#"
#
A:Start of video (show design with component explorer open)
T:Once you identify sets of identical components, you can create your physical reuse source circuit.
F:Start.mp3
#
A: Circle the IO_Port Groups in Component Explorer
T:This design shows four groups of identical components.
F: Circle_IO_Port_Groups.mp3
#
解决方案
当您查看open()函数的 Python 文档时,您会看到它有一个用于文件编码的附加参数,当以文本模式打开文件时,该参数变得相关。
https://docs.python.org/3/library/functions.html#open
使用这个附加参数,您可以将编码类型定义为“utf-8”或“utf8-sig”,您应该能够很好地阅读文本,甚至看不到垃圾字符。
推荐阅读
- html - Shopify 上产品块的交替背景颜色?
- youtube - 具有自定义 URL 但 URL 中没有“c/” slug 的 YouTube 频道不会从 channels.list 端点返回 snippet.customUrl 道具
- javascript - 如何使用 VueJS 将 Outlook 消息拖放到浏览器中
- python - urllib.error.HTTPError:HTTP 错误 404:即使 url 存在,使用 pandas 也找不到
- python - 如何在 Python 中遍历 N 级嵌套字典?
- python - 无法访问位于远程服务器中的 jupyter notebook
- ruby-on-rails - 为什么删除代码行会在 simple_form 中产生“nil:NilClass 的未定义方法‘错误’”
- java - PersistenceContext 和 EntityManager nullPointerException
- javascript - (节点:30437)UnhandledPromiseRejectionWarning:错误:回调函数对承诺客户端不可用
- python - 嵌套具有相同迭代次数的循环的最佳方法是什么?