我有一个输入文件,上面有这样的句子:
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.']
这里似乎有什么问题?
答案 0 :(得分:3)
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]
答案 1 :(得分:2)
尝试:
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.']
答案 2 :(得分:0)
它取整个句子而不是单个单词,尝试迭代w然后检查长度。