【问题标题】:How to split sentences in a list?如何拆分列表中的句子?
【发布时间】:2020-10-23 02:37:29
【问题描述】:

我正在尝试创建一个函数来计算任何给定句子中的单词数和单词的平均长度。假设句子有句号并结束句子,我似乎无法将字符串分成两个句子放入列表中。

  • 问号和感叹号应替换为句点,以被识别为列表中的新句子。
  • 例如:"Haven't you eaten 8 oranges today? I don't know if you did." 将是:["Haven't you eaten 8 oranges today", "I don't know if you did"]
  • 此示例的平均长度为 44/12 = 3.6
def word_length_list(text):
    text = text.replace('--',' ')

    for p in string.punctuation + "‘’”“":
        text = text.replace(p,'')

    text = text.lower()
    words = text.split(".")
    word_length = []
    print(words)

    for i in words:
        count = 0
        for j in i:
            count = count + 1
        word_length.append(count)
    
    return(word_length)

testing1 = word_length_list("Haven't you eaten 8 oranges today? I don't know if you did.")
print(sum(testing1)/len(testing1))

【问题讨论】:

标签: python


【解决方案1】:

一个选项可能使用re.split

inp = "Haven't you eaten 8 oranges today? I don't know if you did."
sentences = re.split(r'(?<=[?.!])\s+', inp)
print(sentences)

打印出来:

["Haven't you eaten 8 oranges today?", "I don't know if you did."]

我们也可以使用re.findall:

inp = "Haven't you eaten 8 oranges today? I don't know if you did."
sentences = re.findall(r'.*?[?!.]', inp)
print(sentences)  # prints same as above

请注意,在这两种情况下,我们都假设句点 . 仅作为停止出现,而不是作为缩写的一部分。如果句号可以有多个上下文,那么将句子分开可能会很棘手。例如:

Jon L. Skeet earned more point than anyone.  Gordon Linoff also earned a lot of points.

这里不清楚句号是指句末还是缩写的一部分。

【讨论】:

  • 如何将它添加到我提供的代码中?当我尝试使用它时出现错误。谢谢!句号也代表句子的结尾
  • def word_length_list(text): 下,只需将我的代码sn-p 中的inp 替换为text,它应该可以工作。
【解决方案2】:

使用正则表达式进行拆分的示例:

import re
s = "Hello! How are you?"
print([x for x in re.split("[\.\?\!]+",s.strip()) if not x == ''])

【讨论】:

  • 如果您将.strip() 移动到re.split(),您将获得稍好的结果。 - 我假设你想跳过真正的空白行和只包含空格的行。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-06-13
  • 1970-01-01
  • 1970-01-01
  • 2017-08-03
  • 1970-01-01
  • 2014-03-04
  • 1970-01-01
相关资源
最近更新 更多