简体   繁体   English

如何创建一个包含文件中每一行的第一个单词的列表(Python 3)

[英]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.

相关问题 如何使用 python 获取文件每一行的第一个单词? - How to get just the first word of every line of file using python? 如何使用 python 创建每个单词列表? - How to use python to create every word list? 如何将每行的第一个单词读入文件中的一行 - How to read first word of every line, into one line in a file 你如何使用python只读取每行文件的第一个单词? - How can you read just the first word of every line of file using python? 将我文件中每一行的第三个单词分配给 Python 中的列表 - Assign the third word of every line in my file to a list in Python 如何用python列表中的相应元素替换文件中每行的第一个单词? - How to replace first word of each line in a file with the corresponding element from a list in python? 如何在Python中将文件中的每一行逐字读取到列表中 - How to read each line from a file into list word by word in Python 替换文本文件(注释文件)中每一行的第一个单词(标签)-Python代码 - Replacing first word (label) of every line in a text file (annotation files)-Python Code 如何使用python更改文件中每个新行的第一个字符 - How to change the first charcater of every new line in a file using python 如果包含某个单词,如何列出文件列表,但如果包含其他单词,则使用 glob python 排除? - How to list down the list of file if contains certain word but exclude if contain other word using glob python?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM