【问题标题】:Split \xef\xbb\xbf in a list read from a file [duplicate]在从文件读取的列表中拆分 \xef\xbb\xbf [重复]
【发布时间】:2016-03-22 04:07:07
【问题描述】:

我尝试读取大数据file.txt并拆分所有逗号、点等,所以我在Python中使用以下代码读取文件:

file= open("file.txt","r")
importantWords =[]
for i in file.readlines():
    line = i[:-1].split(" ")
    for word in line:
        for j in word:
            word = re.sub('[\!@#$%^&*-/,.;:]','',word)
            word.lower()
        if word not in stopwords.words('spanish'):
            importantWords.append(word)
print importantWords

它打印了['\xef\xbb\xbfdataText1', 'dataText2' .. 'dataTextn']

如何清理\xef\xbb\xbf?我正在使用 Python 2.7。

【问题讨论】:

  • 您是否费心寻找那个特定的字符串?

标签: python python-2.7 stop-words


【解决方案1】:

我是UTF-8 encoded BOM

>>> import codecs
>>> codecs.BOM_UTF8
'\xef\xbb\xbf'

您可以使用 codecs.openencoding='utf-8-sig' 来跳过 BOM 序列:

with codecs.open("file.txt", "r", encoding="utf-8-sig") as f:
    for line in f:
        ...

旁注:不要使用file.readlines,而是遍历文件。 file.readlines 将创建不必要的临时列表,如果您想要的只是遍历文件。

【讨论】:

  • 对于 Python 2.7 及更高版本,io.open 通常优于 codecs.open(它更快且通常更正确;例如,codecs.open 不进行行尾转换)。
猜你喜欢
  • 2013-09-10
  • 1970-01-01
  • 2013-01-06
  • 2018-10-12
  • 2019-03-24
  • 1970-01-01
  • 1970-01-01
  • 2012-06-24
相关资源
最近更新 更多