簡體   English   中英

按字長過濾列表

[英]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)

但輸出文件保留所有單詞。 那么有沒有更有效的方法來做到這一點?

  • 使用with-statement自動關閉文件(即使遇到異常)。
  • &在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)

這樣做有多種選擇。

  1. 具有filter()內置功能

這里查看文檔。

假設你有一個名為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每個元素。

  1. 使用列表理解

這可能是實現這一目標的最短途徑。 只需要這樣做:

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.

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