簡體   English   中英

從python的字符串列表中刪除不包含字母的字符串

[英]Removing a string that does not contain letters from a list of strings in python

我正在用python創建文本分析器。 我正在嘗試從該列表中刪除任何不包含任何字母或整數的字符串。 我被卡住了,不知道該怎么做。 目前,在計算列表的長度時,它包括字符串“-”,我不希望這樣,因為我不想將此視為一個單詞。 但是我寧願不使用string.remove('-'),因為我希望它能用於其他輸入。

提前致謝。

我認為您的意思是您要從字符串列表中過濾掉沒有字母數字字符的字符串。 所以['a','b','*'] => ['a','b']

不是太難:

In [39]: l = ['adsfg','sdfgb','gdc','56hjfg1','&#$%^',"asfgd3$#$%^" ]
In [40]: l = filter (lambda s:any([c.isalnum() for c in s]), l)
Out[41]:  ['adsfg', 'sdfgb', 'gdc', '56hjfg1', 'asfgd3$#$%^']

In [42]: 

如果要保留字符串中包含字母數字字符,但其中包含非字母數字字符:

import re

strings = ["string", "&*()£", "$^TY?", "12345", "2wE4T", "@#~\!", "^(*4"]

strings = [s for s in strings if re.search(r'\w+', s)] #  \w matches alphanumeric chars

print strings
['string', '$^TY?', '12345', '2wE4T', '^(*4'] # now we can work with these wanted strings

否則,僅保留完全字母數字字符填充的字符串:

str.isalnum()是你的男人:

strings = [s for s in strings if s.isalnum()]
print strings
['string', '12345', '2wE4T']

有關模塊的更多信息:

https://docs.python.org/2/howto/regex.html

http://www.regular-expressions.info/tutorial.html

暫無
暫無

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

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