简体   繁体   English

在将外部.txt文件转换为Python中的列表时遇到问题?

[英]Problems converting an external .txt file into a List in Python?

I have a .txt file with some strings like this: 我有一个.txt文件,其中包含一些这样的字符串:

word_1
word_2
word_3
....
word_n
word_n-1

I would like to read them and place them into list, in order to do something like this: 我想阅读它们并将它们放入列表中,以便执行以下操作:

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

This is what I tried: 这是我尝试的:

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

But I get this error: 但是我得到这个错误:

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

What would be a better way to do this and how can I deal with the encoding of this extarnal .txt file?. 有什么更好的方法可以做到这一点,如何处理这个出色的.txt文件的编码?

I think you need something like this: 我认为您需要这样的东西:

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

The result is: 结果是:

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

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

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