簡體   English   中英

閱讀txt文件python時從行追加單詞

[英]append word from line when reading txt file python

我正在嘗試創建一個程序,該程序將讀取文本文件並創建單詞行列表。

但是,只能附加每行而不是單詞,對此問題的任何幫助將不勝感激。

text = open("file.txt","r")

for line in text.readlines():
    sentence = line.strip()
    list.append(sentence)

    print list 
text.close()

示例文字

I am here
to do something

我想要它像這樣附加

[['I','am','here']['to','do','something']]

提前致謝。

示例中的每一line只是一個字符串,因此,

...
    PUNCTUATION = ',.?!"\''
    words = [w.strip(PUNCTUATION) for w in line.split() if w.strip(PUNCTUATION)]
    list.append(words)
...

盡管可能無法以您想要的方式涵蓋所有邊緣情況(例如,帶連字符的單詞,不由空格分隔的單詞,帶有撇號的單詞等),但對第一近似方法可能沒問題。

條件是避免空白條目。

您到底從哪里獲得y變量?

從最基本的意義上講(因為您尚未完全指定使用標點符號),您可以使用line.split(' ')將每一行分成單詞列表,該列表在每個空格處進行分割。 如果您還有其他定界符,則可以用它代替空格。 如果需要,將上述拆分分配給var並將其附加到列表中。

@Brendan提供了一種很好的解決方案,以消除基本的標點符號。 或者,您也可以使用簡單的正則表達式re.findall(r'\\w+', file)查找給定文件中的所有單詞。

使用另一種方式,您可以利用string.punctuation string庫,尤其是string.punctuation

str = list(line)
''.join([ word for word in str if not word in string.punctuation ]).split()

這樣的事情會涉及很多情況,並且可以針對您使用的符號進行定制:

import re
text = open("file.txt","r")

for line in text.readlines():
    sentence = line.strip()
    words = re.sub(" +"," ",re.sub("[^A-Za-z']"," ",sentence)).split()
    somelist.append(words)

    print list 
text.close()

這將僅包括大寫字母,小寫字母和撇號(出於收縮的目的)

>>> with open("file.txt","r") as f:
...     map(str.split, f)
... 
[['i', 'am', 'here'], ['to', 'do', 'something']]
text = open("file.txt","r")

word_groups = []

for line in text.readlines():
    words = line.strip().split(' ')
    word_groups.append(words)

print word_groups

text.close()

似乎您只是缺少對str.split()的調用。 這是一個簡單的單行列表理解功能 ,可以滿足您的要求:

>>> [line.split() for line in open('file.txt')]
[['i', 'am', 'here'], ['to', 'do', 'something']]

暫無
暫無

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

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