【问题标题】:Problems converting an external .txt file into a List in Python?在 Python 中将外部 .txt 文件转换为列表时出现问题?
【发布时间】:2015-02-17 01:03:10
【问题描述】:

我有一个 .txt 文件,其中包含如下字符串:

word_1
word_2
word_3
....
word_n
word_n-1

我想阅读它们并将它们放入列表中,以便执行以下操作:

my_words = set(['word_1',...,'word_n-1'])

这是我尝试过的:

with open('/path/of/the/.txt') as f:
   lis = set([int(line.split()[0]) for line in f])
   print lis

但我收到此错误:

    lis = set([int(line.split()[0]) for line in f])
ValueError: invalid literal for int() with base 10: '\xc3\xa9l'

有什么更好的方法来做到这一点,我该如何处理这个外部.txt 文件的编码?。

【问题讨论】:

  • 字是字节格式的吗?
  • 您不能将“单词”转换为整数,除非您的单词是数字“1”、“34”等。
  • 去掉int调用应该没问题。
  • 感谢各位的帮助。 @GLHF 单词只是在一个 txt 文件中(utf-8)

标签: python list python-2.7 encoding io


【解决方案1】:

我认为你需要这样的东西:

with open('file.txt') as f:
    lis = set(line.strip() for line in f)
    print lis

结果是:

set(['word_3', 'word_2', 'word_1', 'word_21', 'word_123'])

【讨论】:

  • 感谢您的帮助!这对如何解决编码问题有任何想法?例如,当我运行它时,我遇到了一些编码问题:'manifest\xc3\xb3', 'ellas', 'estuvo', 'agreg\xc3\xb3'。它们是西班牙语单词。
  • 可能你需要看看编码。例如here.
  • 这不是编码问题,它是 repr 输出打印它看起来像 manifestó
  • 所以单词的编码还是一样的?这只是因为我在 pycharm 终端上打印结果而发生的?
  • @johndoe 也许是它的新问题。新问题可能更合适。如果您决定创建一个新文件,链接到感兴趣的文件或其示例会很有用。
猜你喜欢
  • 1970-01-01
  • 2017-02-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-09-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多