我寫了一個函數,該函數應該將.txt
中的單詞添加到list
,但它應該忽略空行,我的函數如何在空行輸出['',]
。將單詞添加到列表
def words(filename):
word = []
file = open(filename)
for line in file:
word.append(line.strip())
return word
我怎麼能解決這個感謝
我寫了一個函數,該函數應該將.txt
中的單詞添加到list
,但它應該忽略空行,我的函數如何在空行輸出['',]
。將單詞添加到列表
def words(filename):
word = []
file = open(filename)
for line in file:
word.append(line.strip())
return word
我怎麼能解決這個感謝
你需要測試一個空行,並跳過在這種情況下追加。
def words(filename):
word = []
file = open(filename)
for line in file:
line=line.strip()
if len(line):
word.append(line)
return word
yup感謝你發現 - 現在編輯它 – heroworkshop
此外,你可以做'if line:',如果len(line)'更簡單也更高效,並且看到我對關於關閉文件的問題的評論。 –
怎麼樣一個簡單的測試,如果?
def words(filename):
word = []
file = open(filename)
for line in file:
if line.strip() != ' ':
word.append(line.strip())
return word
編輯:我行 除了後忘了.strip(),你也可以使用if line.strip():
最後,如果你想獲得一個單詞列表,但每行有幾個單詞,你需要將它們分割。假設你的分隔符'「:
def words(filename):
word = []
file = open(filename)
for line in file:
if line.strip() != ' ':
word.extend(line.strip().split())
return word
除了你會不會考慮包含空白也爲空線一條線嗎?一個流浪「」字,你仍然會得到空條目OP在抱怨 – heroworkshop
@heroworkshop謝謝,我糾正我的答案。另外請注意,如果你想從句子中得到單詞,你可能需要導入're'並找到正確的正則表達式(一定不要太複雜) – Wli
可以解決這個問題這樣的:
def words(filename):
word = []
file = open(filename)
for line in file:
if not line.strip():
word.append(line)
return word
你的問題是,您要添加line.strip()
,但如果line
實際上是一個空字符串,會發生什麼?看:
In [1]: line = ''
In [2]: line.strip()
Out[2]: ''
''.strip()
返回一個空字符串。
我認爲OP想要追加剝離的線,而不是未剝離的線。 –
@ PM2Ring如果是這種情況,我相信OP能夠改變爲'word.append(line.strip()'。 – Maroun
關閉打開的文件是一種很好的做法。或者在'with'塊中打開文件,以便它自動關閉。 –
我仍然在做這個工作,只是卡住在這個部分 – James