[英]Filter list by length of words
我試圖通過單詞的長度(4到8個字符之間)逐行過濾列表。 因此,如果輸入文件具有:
輸出文件是:
所以我有這個代碼:
dir = "lower.lst"
dict = open(dir, 'r').readlines()
f=open('dictionary','w')
for word in dict:
if len(word)>=4 & len(word)<=8:
f.write(word)
f.close()
print(len(dict))
print(f)
但輸出文件保留所有單詞。 那么有沒有更有效的方法來做到這一點?
&
在Python中真的只是為了苦惱,使用and
。 and
,因為比較可以鏈接。 ( len(word)>=4 and len(word)<=8
相當於4 <= len(word) <= 8
)。 .readlines()
,在這里我使用for line in fin:
無論哪種方式,結果字符串都將以換行符結尾,因此您的長度測量結果將為1。 我通過在獲取長度之前剝離線來解決這個問題( len(line.strip())
)。 (你寫的代碼應該省略'be'
,但保留'dog'
,因為它實際上是'dog\\n'
,其長度為4)。 'communication\\n'
和'be\\n'
。 我可以想象,如果文件中有額外的空格,那么'be\\n'
可能會被保留(由於這兩個空格, 'be \\n
'的長度為5)。 但似乎沒有邏輯方法可以將'communication\\n'
保存在輸出文件中。 您可能需要仔細檢查它確實存在。 with open('lower.lst', 'r') as fin, open('dictionary', 'w') as fout:
for line in fin:
if 4 <= len(line.strip()) <= 8:
fout.write(line)
這樣做有多種選擇。
在這里查看文檔。
假設你有一個名為data
的字符串列表,然后:
data = ['hello', 'communication', 'be', 'dog', 'test']
filtered_list = filter(lambda x: len(x) > 4 and len(x) < 8, data)
print(filtered_list)
將返回:
Python 3.6.1 (default, Dec 2015, 13:05:11)
[GCC 4.8.2] on linux
>
['hello']
您可以更改lambda函數以過濾不同的條件。 Filter將“捕獲”返回True
每個元素。
這可能是實現這一目標的最短途徑。 只需要這樣做:
filtered_list = [x for x in data if len(x) > 4 and len(x) < 8]
列表理解確實允許您選擇要從中構建列表的元素。 這是一個示例實現:
s = """
hello
communication
be
dog
test
"""
lst = [elm for elm in s.split() if (len(elm) >= 4 and len(elm) <= 8)]
print(lst)
輸出:
['hello', 'test']
這是你在找什么? 這里我使用with
保留字的文件上下文管理器,我使用and
不是注釋中注明的&
。
with open("lower.lst", "r") as f:
o = [word for word in f if (len(word) >= 4 and len(word) <= 8)]
with open("outfile.lst", "w") as f:
f.write(o)
要知道這是否會完全符合您在outfile中的意圖,這有點難以理解。
如果你替換&
for and
你的代碼應該工作,即:
dict = open("lower.lst", 'r').readlines()
with open('dictionary','w') as f:
for word in dict:
if len(word)>=4 and len(word)<=8:
f.write(word)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.