作者:手机用户2502902993 | 来源:互联网 | 2022-12-07 01:49
1> Black Thunde..:
我已经制作了一个按预期工作的小代码:
city=['Venango Municiplaity', 'Waterford ship','New York']
comwo = ['ship','municipality']
for i, c in enumerate(city):
for ii in comwo:
if ii in c:
city.append(city[i].replace(ii,""))
print(city)
输出:
['Venango Municiplaity', 'Waterford ship', 'New York', 'Waterford ']
注意:
您所做的列表包含错误的拼写.
查看list city
的第一个元素Venango
Municiplaity
和common_words的第二个元素municipality
编辑:
因此,如果您还想替换单词后面的空格(如果有的话),那么我已经创建了一个单独的代码:
[city.append(city[i].replace(ii,"")) for ii in comwo for i, c in enumerate(city) if ii in c]
输出:
city=['Village home', 'Villagehome','New York']
comwo = ['home']
for i, c in enumerate(city):
for ii in comwo:
if ii in c:
city.append(city[i].replace(" "+ii,"")) if city[i].replace(" "+ii,"") != city[i] else city.append(city[i].replace(ii,""))
print(city)
@ min2bro它也取代了单词中的单词,例如:Villageship to village.并且它不会删除尾随空格.它区分大小写.
2> Laurent H...:
我建议你使用以下解决方案,使用re.sub
with flags=re.IGNORECASE
来删除忽略大小写的常用词:
import re
city = ['Venango Municipality', 'Waterford ship','New York']
common_words = ['ship','municipality']
toAppend = []
for c in city:
for cw in common_words:
if cw.lower() in c.lower().split():
toAppend.append(re.sub(cw, "", c, flags=re.IGNORECASE).strip())
city += toAppend
print(city) # ['Venango Municipality', 'Waterford ship', 'New York', 'Venango', 'Waterford']
这是使用列表理解的单行样式解决方案,简短但可读性较差:
import re
city = ['Venango Municipality', 'Waterford ship','New York']
common_words = ['ship','municipality']
city += [re.sub(cw, "", c, flags=re.IGNORECASE).strip() for c in city for cw in common_words if cw.lower() in c.lower().split()]
print(city) # ['Venango Municipality', 'Waterford ship', 'New York', 'Venango', 'Waterford']
3> Bear Brown..:
您可以尝试它,创建新列表以保存数据应该添加到您的原始列表,然后连接结果:
In [1]: city=['Venango Municiplaity', 'Waterford ship','New York']
In [2]: common_words = ['ship', 'municiplaity']
In [3]: list_add = []
In [4]: for item in city:
...: item_words = [s.lower() for s in item.split(' ')]
...: if set(common_words) & set(item_words):
...: new_item = [s for s in item.split(' ') if s.lower() not in common_words]
...: list_add.append(" ".join(new_item))
...:
In [5]: city + list_add
Out[5]: ['Venango Municiplaity', 'Waterford ship', 'New York', 'Venango', 'Waterford']