【问题标题】:Python split text without spaces but keep dates as they arePython 拆分没有空格的文本,但保持日期不变
【发布时间】:2021-12-02 04:51:52
【问题描述】:

要分割不带空格的文本,可以使用wordninja,请参阅How to split text without spaces into list of words。这是完成这项工作的代码。

sent = "Test12  to separate mergedwords butkeeprest asitis, say 1/2/2021 or 1.2.2021."

import wordninja
print(' '.join(wordninja.split(sent)))

output: Test 12 to separate merged words but keep rest as it is say 1 2 2021 or 1 2 2021

wordninja 看起来很棒,可以很好地分割那些合并的文本。我的问题是如何在没有空格的情况下拆分文本,但保持日期(和标点符号)不变。理想的输出是:

Test 12 to separate merged words but keep rest as it is, say 1/2/2021 or 1.2.2021

非常感谢您的帮助!

【问题讨论】:

  • 如果没有某种词典/字典来了解实际单词是什么,您将无法真正做到这一点。
  • 为什么不与sent.split()re.split(r"[\W,/]+", sent) 进行基本拆分并从那里获取呢?这些是 Python 内置函数。
  • 只是吐口水,但您也许可以使用正则表达式在原始字符串中找到日期的位置,在字符串的每个不是日期的部分上使用 wordninja,然后组合不同的段?
  • @Jens 我相信这里的想法是 OP 试图拆分的单词可以任意组合,因此将它们与内置函数拆分会......很痛苦

标签: python date text split


【解决方案1】:

这里的想法是在日期的每个实例中将我们的字符串拆分为一个列表,然后遍历该列表,保留与初始拆分模式匹配的项目,并在其他所有内容上调用 wordninja.split()。然后用 join 重新组合列表。

import re
def foo(s):
    return 'ninja'

string = 'Test12  to separate mergedwords butkeeprest asitis, say 1/2/2021 or 1.2.2021.'
pattern = re.compile(r'([0-9]{1,2}[/.][0-9]{1,2}[/.][0-9]{1,4})')

# Split the string up by things matching our pattern, preserve rest of string.
string_isolated_dates = re.split(pattern, string)

# Apply wordninja to everything that doesn't match our date pattern, join it all together. OP should replace foo in the next line with wordninja.split()
wordninja_applied = ' '.join([el if pattern.match(el) else foo(el) for el in string_isolated_dates])

print(wordninja_applied)

输出:

 ninja 1/2/2021 ninja 1.2.2021 ninja

注意:我将您的函数 wordninja.split() 替换为 foo() 只是因为我不想再下载另一个 nlp 库。但我的代码演示了在保留日期的同时修改原始字符串。

【讨论】:

    【解决方案2】:

    最后我得到了以下代码,基于我帖子下的 cmets(感谢 cmets):

    import re
    sent = "Test12  to separate mergedwords butkeeprest asitis, say 1/2/2021 or 1.2.2021."
    sent = re.sub(","," ",sent)
    corrected = ' '.join([' '.join(wordninja.split(w)) if w.isalnum() else w for w in sent.split(" ")])
    print(corrected) 
    
    output: Test 12  to separate merged words but keep rest as it is say 1/2/2021 or 1.2.2021.
    

    这不是一个简单的解决方案,但很有效。

    【讨论】:

    • 哦,这不是我的评论的意思,如果我有机会写一个答案会帮助你吗?
    • 谢谢,0x263A,是的,如果你能写下你的答案就好了。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-07
    • 2016-11-02
    • 1970-01-01
    • 1970-01-01
    • 2016-03-11
    • 2019-08-01
    相关资源
    最近更新 更多