【问题标题】:Extracting only words out of a mixed string in Python [duplicate]在Python中仅从混合字符串中提取单词[重复]
【发布时间】:2020-01-05 09:36:14
【问题描述】:

我正在做一个主题建模任务,并且有以下形式的未知主题

 topic = 0.2*"firstword" + 0.2*"secondword" + 0.2*"thirdword" + 0.2*"fourthword" + 0.2*"fifthword"

我想要一个 regex.findall() 函数返回一个仅包含单词的列表,例如:

['firstword', 'secondword', 'thirdword', 'fourthword', 'fifthword']

我尝试过使用正则表达式函数:

regex.findall(r'\w+', topic)  and 
regex.findall(r'\D\w+', topic)

但它们都不能正确消除数字。 有人可以帮我找出我做错了什么吗?

【问题讨论】:

  • 什么是topicstr?
  • 是的主题是'str'类型
  • @SoumyaChakraborty 你能分享topic 字符串的实际值吗?是'0.2*"firstword" + 0.2*"secondword" + 0.2*"thirdword" + 0.2*"fourthword" + 0.2*"fifthword"'吗?
  • 如果我输入 print(topic) 它会显示:0.2*"firstword" + 0.2*"secondword" + 0.2*"thirdword" + 0.2*"fourthword" + 0.2*"fifthword"

标签: python regex


【解决方案1】:

如果topic 是字符串

topic = '0.2*"firstword" + 0.2*"secondword" + 0.2*"thirdword" + 0.2*"fourthword" + 0.2*"fifthword"'

那么下面的正则表达式会返回你所需要的

re.findall('"(.*?)"', topic)

它查找包含在双引号 (") 中的所有字符串

【讨论】:

    【解决方案2】:

    你可以尝试两种方式:

    第一个更简单的方法是遍历字符串并只保留这样的字母:

    ''.join(letter for letter in topic if letter.isalpha())
    

    否则你可以像这样使用正则表达式:

    re.sub('[^a-zA-Z]+', '', topic)
    

    这个表达式只保留字母 il 小写和大写。

    【讨论】:

      【解决方案3】:

      我自己也遇到过这个问题。我的解决方案是:

          import re
      
          def extract_tokens_from_topic(self, raw_topic):            
              raw_topic_string = raw_topic.__str__() # convert list to string
              return re.findall(r"'(.*?)'", raw_topic_string)
      

      raw_topic 来自raw_topic = lda_model.show_topic(topic_no)

      【讨论】:

        【解决方案4】:

        这是一种方法:

        >>> import re
        
        >>> topic = "0.2*firstword" + "0.2*secondword" + "0.2*thirdword" + "0.2*fourthword" + "0.2*fifthword"
        
        >>> re.sub(r'[ˆ\d]\W',' ', topic).strip().split()
        >>> ['firstword', 'secondword', 'thirdword', 'fourthword', 'fifthword']
        

        【讨论】:

        • 概率不在双引号内,只是组成的单词在,但无论如何我明白了你的意思。谢谢
        猜你喜欢
        • 1970-01-01
        • 2021-12-19
        • 2019-05-21
        • 1970-01-01
        • 2021-09-23
        • 2017-11-09
        • 1970-01-01
        • 2017-02-04
        • 1970-01-01
        相关资源
        最近更新 更多