[英]How to create a list that contains the first word of every line in a file (Python 3)
The file is called "emotion_words" which I want the first word of each line for. 该文件称为“ emotion_words”,我希望将其作为每行的第一个单词。 I want to use a nested for loop, but I am not sure how.
我想使用嵌套的for循环,但不确定如何。 Would I do this
我会这样做吗
emotions=open("emotion_words.txt","r+")
content = emotions.read()
for line in content.split(' ',1):
And add an append function before the second for loop? 并在第二个for循环之前添加一个append函数?
with open("emotion_words.txt","r+") as f:
for line in f:
first_word_in_line = line.split(" ")[0]
fileref = open ("emotion_words.txt","r")
line = fileref.readlines()
emotions = []
for words in line:
word = words.split()
emotions.append(word[0])
print (emotions)
If I understand you question correctly, this should work for you: 如果我理解您的问题正确无误,那么这应该对您有用:
words = []
emotions = open("emotion_words.txt", "r+")
for l in emotions:
first_word = l.split()[0]
words.append(first_word)
After that you have your words in a 'words' list. 之后,将您的单词放入“单词”列表中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.