簡體   English   中英

需要使用 python 刪除列表中具有特定分隔符的單詞

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

需要從每個單詞中刪除單詞分隔字符(例如, . - * !空格),存在於列表單詞中。 將得到的結果再次存儲在列表詞中。

我似乎無法刪除單詞列表中的整個單詞。 有這樣的事嗎? 我嘗試了下面的代碼,但它不會刪除帶有上述字符的單詞。 另外,我是否需要使用列表理解和剝離函數。

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

嘗試這個:

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

output:

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

也就是說,如果你想拆分單詞,如果你只想刪除字符,你可以使用.replace()

strip()只會從字符串的開頭或結尾刪除這些字符。 您需要使用translate()或更復雜的基於正則表達式的替換re.sub()

使用deletechars參數的translate()示例:

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

re.sub()的例子:

import re

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

Output:

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

如建議的那樣,如果您的目標是從字符串列表中刪除字符,則可以將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