【问题标题】:How to replace random elements of a list with a unique symbol?如何用唯一符号替换列表的随机元素?
【发布时间】:2019-08-24 22:41:46
【问题描述】:

我是 python 编程的新手。我有两个列表,第一个列表包含停用词,另一个包含文本文档。我想用“/”替换文本文档中的停用词。有没有人可以帮忙?

我用了replace函数,报错了

text = "This is an example showing off word filtration"
stop = `set`(stopwords.words("english"))
text = nltk.word_tokenize(document)

`for` word in stop:
    text = text.replace(stop, "/")
`print`(text)

它应该输出 "///示例显示/单词过滤"

【问题讨论】:

    标签: python-3.x


    【解决方案1】:

    list comprehension怎么样:

    >>> from nltk.corpus import stopwords
    >>> from nltk.tokenize import word_tokenize  
    >>> stop_words = set(stopwords.words('english'))
    >>> text = "This is an example showing off word filtration"
    >>> text_tokens = word_tokenize(text) 
    >>> replaced_text_words = ["/" if word.lower() in stop_words else word for word in text_tokens]
    >>> replaced_text_words
    ['/', '/', '/', 'example', 'showing', '/', 'word', 'filtration']
    >>> replaced_sentence = " ".join(replaced_text_words)
    >>> replaced_sentence
    / / / example showing / word filtration
    

    【讨论】:

      【解决方案2】:

      使用正则表达式模式怎么样?

      您的代码可能如下所示:

      from nltk.corpus import stopwords
      import nltk
      
      text = "This is an example showing off word filtration"
      text = text.lower()
      
      
      import re
      pattern = re.compile(r'\b(' + r'|'.join(stopwords.words('english')) + r')\b\s*')
      text = pattern.sub('/ ', text)
      

      关于这个post

      【讨论】:

      • This 是一个停用词,它与您的正则表达式不匹配,因为它不是完全小写的,即停用词语料库仅包含小写单词。
      • 你是绝对正确的。非常感谢!我更新了上面的代码。
      【解决方案3】:

      您应该在替换函数中使用word 而不是stop

      for word in stop:
          text = text.replace(word, "/")
      

      【讨论】:

        【解决方案4】:

        你可以试试这个

        ' '/join([item if item.lower() not in stop else "/" for item in text ])
        

        【讨论】:

          猜你喜欢
          • 2018-02-19
          • 1970-01-01
          • 1970-01-01
          • 2021-02-19
          • 2014-02-15
          • 2019-03-25
          • 2022-01-11
          • 2018-10-08
          • 1970-01-01
          相关资源
          最近更新 更多