替换列表中的单词并附加到同一列表中

我的列表:


city=['Venango Municiplaity', 'Waterford ship','New York']

预期结果:


city = ['Venango Municiplaity ', 'Waterford ship','New York','Venango','Waterford']

常用的词:


common_words = ['ship','municipality']

扫描我的列表中的所有项目,去掉常用词并重新插入到同一个列表中,如预期结果所示。


我能够搜索包含常用词的项目,但不确定如何将其替换为空白并重新插入“我的列表”中。


到目前为止我的代码:


for item in city:

    if(any(x in s.lower() for s in item.split(' ') for x in common_words)) :


叮当猫咪
浏览 157回答 3
3回答

神不在的星期二

我建议您使用以下解决方案,使用re.subwithflags=re.IGNORECASE去除忽略大小写的常用词:import recity = ['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 += toAppendprint(city) # ['Venango Municipality', 'Waterford ship', 'New York', 'Venango', 'Waterford']这是一个使用列表理解的单线样式解决方案,虽然简短,但可读性较差:import recity = ['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']

四季花海

您可以尝试一下,创建新列表以保存数据,应将数据添加到原始列表中,然后合并结果: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_addOut[5]: ['Venango Municiplaity', 'Waterford ship', 'New York', 'Venango', 'Waterford']
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python