首页 > 解决方案 > 如何在 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
#

标签: pythonutf-8strip

解决方案


当您查看open()函数的 Python 文档时,您会看到它有一个用于文件编码的附加参数,当以文本模式打开文件时,该参数变得相关。

https://docs.python.org/3/library/functions.html#open

使用这个附加参数,您可以将编码类型定义为“utf-8”或“utf8-sig”,您应该能够很好地阅读文本,甚至看不到垃圾字符。


推荐阅读