簡體   English   中英

如何創建一個包含文件中每一行的第一個單詞的列表(Python 3)

[英]How to create a list that contains the first word of every line in a file (Python 3)

該文件稱為“ emotion_words”,我希望將其作為每行的第一個單詞。 我想使用嵌套的for循環,但不確定如何。 我會這樣做嗎

emotions=open("emotion_words.txt","r+")
content = emotions.read()
for line in content.split(' ',1):

並在第二個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)

如果我理解您的問題正確無誤,那么這應該對您有用:

words = []
emotions = open("emotion_words.txt", "r+")
for l in emotions:
    first_word = l.split()[0]
    words.append(first_word)

之后,將您的單詞放入“單詞”列表中。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM