【问题标题】:Removing list of words and replace删除单词列表并替换
【发布时间】:2019-01-18 23:53:12
【问题描述】:

请帮帮我。

  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']

【问题讨论】:

  • 如果你在字典中反转你的键/值会更清楚,所以{ 'north': 'n', 'northern': 'n' ... }等。它也会让你的代码更容易维护。

标签: python list dictionary replace split


【解决方案1】:

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

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']

【讨论】:

  • NameError: name 'result' is not defined
  • 当然,result 是 OP 代码的结果。我看过你的编辑。我有同样的想法,但我想在之后添加替代方案(多合一代码)。您通常不应该在编辑中提出更好的解决方案(cmets 对此更好),所以我应该拒绝它,但我只是打算改进它。
  • @Jean-FrançoisFabre 感谢您的大力帮助。我需要更多帮助。完成上述两个步骤后,最后我想输出应该打印前 20 个字符(包括空格) Ex ['my name alan from london Southeast'] 应该打印 ['my name alan come from londo']。请回答这对我有很大帮助。
  • 只切片结果字符串:[x[:20] for x in result]
  • @Jean-FrançoisFabre 以及上面的输出我想删除标点符号 (!"#$%&'()*+,-./:;?@[]^_@987654328 @{|}~] result = [" ".join([rev_dict.get(x,x) for x in s.split() if x not in zip(stopwords,punct)]) for s in search_list]跨度>
猜你喜欢
  • 2020-07-29
  • 1970-01-01
  • 1970-01-01
  • 2021-10-29
  • 2021-12-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-08-26
相关资源
最近更新 更多