正在删除单词列表和rep

2024-04-23 22:10:32 发布

您现在位置:Python中文网/ 问答频道 /正文

请帮我一下。你知道吗

  1. 我有一个非索引词列表和搜索列表。我想把它们去掉 停止搜索列表中的单词。你知道吗
  2. 在(步骤1)之后,我想用字典值匹配每个拆分的单词。如果 值匹配用相应的字典键替换特定单词 然后加入其他单词。你知道吗

到目前为止,我已经完成了步骤1(参见下面的代码)。效果很好:

    stopwords=['what','hello','and','at','is','am','i']
    search_list=['where is north and northern side',
                 'ask in the community at western environmental',
                 'my name is alan and i am coming from london southeast']
    dictionary = {'n': ['north','northern'],
                  's': ['south','southern'],
                  'e': ['east','eastern'],
                  'w': ['west','western'],
                  'env': ['environ.','enviornment','environmental']}

    result = [' '.join(w for w in place.split() if w.lower() not in stopwords)
                for place in search_list]

    print (result)

我需要以下理想的最终输出来完成步骤2。为了得到我想要的最终输出,我应该在上面的一行代码中更改/包括什么?任何其他替代方法也欢迎。你知道吗

['where n n side', 'ask in the community w env', 'my name alan coming from london s']

Tags: and代码in列表search字典is步骤
1条回答
网友
1楼 · 发布于 2024-04-23 22:10:32

您必须“反转”词典,因为查找是相反的:

rev_dict = {v:k for k,l in dictionary.items() for v in l}

现在更换方便了:

>>> rev_dict
{'east': 'e',
 'eastern': 'e',
 'enviornment': 'env',
 'environ.': 'env',
 'environmental': 'env',
 'north': 'n',
 'northern': 'n',
 'south': 's',
 'southern': 's',
 'west': 'w',
 'western': 'w'}

再次拆分字符串(您可以保持单词列表的原样以避免拆分),并替换为默认值作为单词,以防不匹配:

result = [" ".join([rev_dict.get(x,x) for x in s.split() if x not in stopwords]) for s in search_list]

或同时删除和替换停止词:

stopwords={'what','hello','and','at','is','am','i'}  # define as a set for fast lookup
result = [" ".join([rev_dict.get(x,x) for x in s.split() if x not in stopwords]) for s in search_list]

在这两种情况下,结果:

['where n n side', 'ask in the community w env', 'my name alan coming from london southeast']

相关问题 更多 >