简体   繁体   English

如何在 UTF-8 文件开头去除垃圾字符

[英]How do I strip garbage characters at start of UTF-8 file

I have the following code in Python 3.9 and it works, except that I am getting a garbage character at the start of my UTF-8 encoded text file that is making it incorrectly read the first character of the first line.我在 Python 3.9 中有以下代码并且它可以工作,除了我在我的 UTF-8 编码文本文件的开头得到一个垃圾字符,这使它错误地读取了第一行的第一个字符。 How do I strip any garbage characters at the beginning of the UTF-8 file that I am reading?如何删除我正在阅读的 UTF-8 文件开头的任何垃圾字符?

Here is the code:这是代码:

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}')

Here is a sample of the input file - there is more to the code, it always looks at the first character of the line and, based on that character, performs a specific action:这是输入文件的示例 - 代码有更多内容,它始终查看行的第一个字符,并根据该字符执行特定操作:

#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
#

When you look at the Python documentation for the open() function, you will see that it has an additional argument for the file's encoding, which becomes relevant when a file is opened in text mode.当您查看open()函数的 Python 文档时,您会看到它有一个用于文件编码的附加参数,当以文本模式打开文件时,该参数变得相关。

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

Using this additional argument, you can define the encoding type as "utf-8" or "utf8-sig" and you should be able to read the text just fine, without even seeing the garbage characters.使用这个附加参数,您可以将编码类型定义为“utf-8”或“utf8-sig”,您应该能够很好地阅读文本,甚至看不到垃圾字符。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM