【问题标题】:Python3 textcoding issue: extra first character when reading from text file using for loopPython3 文本编码问题:使用 for 循环从文本文件中读取时出现多余的第一个字符
【发布时间】:2021-04-14 10:25:51
【问题描述】:

我正在尝试从文本文件中读取多个股票代码,但似乎存在文本编码问题。

这是测试文件“tickers.txt”的内容:

SPG
WBA

这是我的测试代码:

    f = open("tickers.txt", 'r')
    for ticker in f:
        t = ticker.strip()
        if t:
          try:
            print(">"+t+"<" + ' length = '+ str(len(t)))
            i = 0
            while i < len(t):
              print(t[i])
              i += 1
            print('End')
          except ValueError:
            print('ValueError ticker')

这是结果输出:

>SPG< length = 4

S
P
G
End
>WBA< length = 3
W
B
A
End

由于某种原因,第一个股票代码中有一个额外的字符,打印时不显示。已经阅读了 StackOverflow 上的几个问答,我现在认为这是一个文本编码问题,但还不明白如何解决这个问题......我需要在文件打开命令中添加一个“编码”语句吗?如果有,是哪一个?如何检测?

【问题讨论】:

    标签: python-3.x for-loop encoding text-files string-length


    【解决方案1】:

    将print(t[i])更改为print(i, t[i], '{:04x}'.format(ord(t[i]))),我可以得到以下输出,表明额外的第一个字符是Byte order mark。

    >SPG< length = 4
    0  feff
    1 S 0053
    2 P 0050
    3 G 0047
    End
    >WBA< length = 3
    0 W 0057
    1 B 0042
    2 A 0041
    End
    

    使用utf_8_sig — UTF-8 codec with BOM signature。解码时,将跳过数据开头的可选 UTF-8 编码 BOM。

    f = open("tickers.txt", mode='r', encoding='utf_8_sig')
    

    而不是

    
    
    f = open("tickers.txt", 'r')
    
    

    顺便说一句,别忘了f.close() ...

    【讨论】:

    • 谢谢 JozefZ !这似乎确实解决了问题。是的,我应该添加 f.close() - 此代码源自 with ....as f: 语句,它会自动关闭文件。所以我是对的,这是一个文本文件编码问题......如何确定要使用哪种编码?之前尝试过找到,但无法得到明确的答案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-01-28
    • 1970-01-01
    • 2015-05-08
    • 2015-08-25
    • 1970-01-01
    • 1970-01-01
    • 2021-10-26
    相关资源
    最近更新 更多