列出 Python 中文本文件中每行的第一个单词

List the first words per line from a text file in Python

我需要 select 每行的第一个词并从文本文件中列出它们:

I would copy the text but it's the formatting is quite screwed up. will try 所有其他文本都是不必要的。

我试过了

string=[]
for line in f:
   String.append(line.split(None, 1)[0]) # add only first word

来自另一个解决方案,但它一直返回 "Index out of bounds" 错误。

我可以使用 string=text.partition(' ')[0] 从第一行获取第一个词 但我不知道如何对其他行重复此操作。

我还是 python 和网站的新手,希望我的格式可以接受! (打开时,我对文本进行编码以接受符号,就像这样 wikitxt=open('racinesPrefixesSuffixes.txt', 'r', encoding='utf-8') 这可能是问题所在吗?)

它引发 IndexError 的原因是因为特定行是空的。 你可以这样做:

words = []
for line in f:
    if line.strip():
        words.append(line.split(maxsplit=1)[0])

此处 line.strip() 正在检查该行是否仅包含空格。如果它只包含空格,它将直接跳过该行。

或者,如果你喜欢list comprehension

words = [line.split(maxsplit=1)[0] for line in f if line.strip()]