简体   繁体   English

需要使用 python 删除列表中具有特定分隔符的单词

[英]Need to remove word with certain separating character in list using python

Need to remove the word separating characters (such as , . - * ! and space ) from each of the word, present in list words.需要从每个单词中删除单词分隔字符(例如, . - * !空格),存在于列表单词中。 Store the obtained result again in the list words.将得到的结果再次存储在列表词中。

I can't seem to remove the whole word in my words list.我似乎无法删除单词列表中的整个单词。 Is there such a thing?有这样的事吗? I tried below code but it wont remove the words with above chars.我尝试了下面的代码,但它不会删除带有上述字符的单词。 Also, can I need to use list comprehension and strip func.另外,我是否需要使用列表理解和剥离函数。

words=([s.strip(",.-*! ") for s in (Convert(setofStrings))])
print(words)

Try this:尝试这个:

b = ["aa-2", "bb-2"]
words = [x.split("-") for x in b]

output: output:

[['aa', '2'], ['bb', '2']]

That is if you want to split the words, if you just want to remove the characters you can use .replace()也就是说,如果你想拆分单词,如果你只想删除字符,你可以使用.replace()

strip() will only remove those characters from beginning or end of string. strip()只会从字符串的开头或结尾删除这些字符。 You need to either use translate() or for more complicated regular expression based substitution re.sub() .您需要使用translate()或更复杂的基于正则表达式的替换re.sub()

Example of translate() using deletechars argument:使用deletechars参数的translate()示例:

words = ['-foo.,', '!b*a-!r', 'ba*!,-z']
words = [s.translate(None, '-.!*,') for s in words]

and example of re.sub() :re.sub()的例子:

import re

words = ['-foo.,', '!b*a-!r', 'ba*!,-z']
words = [re.sub(r'[-\.!\*,]', '', s) for s in words]

Output: Output:

['foo', 'bar', 'baz']

As suggested you could use re.sub in combination with a list comprehension if your aim is to remove the characters from a list of strings.如建议的那样,如果您的目标是从字符串列表中删除字符,则可以将re.sub与列表理解结合使用。

import re
list_of_words = ['test.','cool!','wow ','y*,!']
result = [re.sub('[,\.\-\*\! ]', '', word) for word in list_of_words] 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM