簡體   English   中英

Python:刪除非字母詞

[英]Python: Remove Non-Alphabetical words

我正在使用以下代碼。 為什么我的函數的輸出仍然包含數字值?

功能

def removeNonAplhabet(inputlist):
    for w in inputlist:
        if ((w.isalnum()==True) or ( (w.isdigit()==True))):
            inputlist.remove(w);
     return inputlist;       

主程序

filtered_words=removeNonAplhabet(word_list);
print ('Removing Non Alphabetical Characters')
print (filtered_words)

產量

['13', '1999', '2001', '280', 'amazon', 'another', 'april'] 

迭代序列時刪除項目確實可以正常工作。 制作副本,然后迭代該副本。

或使用列表理解str.isalpha

>>> def removeNonAplhabet(inputlist):
...     return [w for w in inputlist if w.isalpha()]
...
>>> removeNonAplhabet(['13', '1999', '2001', '280', 'amazon', 'another', 'april'])
['amazon', 'another', 'april']

順便說一句, str.isalnum對於僅包含字母的單詞將返回True。

>>> 'abc'.isalnum()
True
>>> '123'.isalnum()
True
>>> 'a,b'.isalnum()
False

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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