简体   繁体   中英

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. I want to use a nested for loop, but I am not sure how. 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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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