【问题标题】:Splitting strings in Python, but with spaces in substrings在 Python 中拆分字符串,但子字符串中有空格
【发布时间】:2017-06-30 15:42:45
【问题描述】:

我有一个字符串,我想将其拆分为特定类型的列表。比如我想把Starter Main Course Dessert拆分成[Starter, Main Course, Dessert]

我不能使用 split() 因为它会拆分 Main Course 类型。我该如何进行拆分?需要正则表达式吗?

【问题讨论】:

  • 您必须知道单词或部分单词或布局才能做到这一点..
  • 什么匹配 Main Course 但不匹配 Starter MainCourse Dessert(来自 Starter Main Course Dessert)?这是不可能的,AFAIK。
  • 是的,我知道要拆分成的单词,但我不确定如何从原始字符串中拆分出来
  • 也许您需要 2-gram(bigram)。在 Python 中,您可以使用 nltkThis 可能会有所帮助。还有thisthis
  • 所以你知道你想保持在一起的所有特定单词,对吧?

标签: python


【解决方案1】:

如果您有一个可接受的单词列表,您可以使用正则表达式联合:

import re

acceptable_words = ['Starter', 'Main Course', 'Dessert', 'Coffee', 'Aperitif']
pattern = re.compile("("+"|".join(acceptable_words)+")", re.IGNORECASE)
# "(Starter|Main Course|Dessert|Coffee|Aperitif)"

menu = "Starter Main Course NotInTheList dessert"
print pattern.findall(menu)
# ['Starter', 'Main Course', 'dessert']

如果您只想指定应该匹配哪些特殊子字符串,您可以使用:

acceptable_words = ['Main Course', '\w+']

【讨论】:

    【解决方案2】:

    我认为只指定“特殊”的两个词标记更实用。

    special_words = ['Main Course', 'Something Special']
    sentence = 'Starter Main Course Dessert Something Special Date'
    
    words = sentence.split(' ')
    for i in range(len(words) - 1):
        try:
            idx = special_words.index(str(words[i]) + ' ' + words[i+1])
            words[i] = special_words[idx]
            words[i+1] = None
        except ValueError:
            pass
    
    words = list(filter(lambda x: x is not None, words))
    print(words)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-02-15
      • 2023-01-13
      • 2019-10-11
      • 1970-01-01
      • 1970-01-01
      • 2020-12-01
      相关资源
      最近更新 更多