[英]Remove words form list sentences that have length < 3
我有一個包含這樣的句子的輸入文件:
I like apples
My mother is called Anna.
我將這些句子轉移到列表中,然后刪除長度小於3的單詞。
我已經試過了:
with open("fis.txt", "r", encoding="utf8") as f:
lst = [w.lower() for w in f.readlines() if len(w) >= 3]
print(lst)
但它給了我['i like apples', 'my mother is called anna.']
我想獲得['like apples', 'mother called anna.']
這里似乎是什么問題?
f.readlines()
為您提供了一個列表,其中包含兩個項,分別對應於文件的兩行。
您需要遍歷各行(無需先將它們讀入內存,只需遍歷f
),分割每一行,然后過濾單詞。
with open("fis.txt", "r", encoding="utf8") as f:
lst = [' '.join(w.lower() for w in line.split() if len(w) >= 3) for line in f]
嘗試:
with open("fis.txt", "r", encoding="utf8") as f:
print( [" ".join(j for j in w.split() if len(j) >= 3 ) for w in f.readlines() ] )
輸出:
['like apples', 'mother called Anna.']
它占用整個句子而不是單個單詞,嘗試遍歷w,然后檢查其長度。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.