2010-07-25 72 views
5

初学者的Python问题:限制字符串中的句子数

我有一个字符串,其中包含x个句子。如何提取第2个句子(可能以。或?或!结尾)

+6

考虑“罗杰斯先生到店里。” :那是两句话吗? – unutbu 2010-07-25 13:53:16

+0

过滤您的句子列表,删除以单个字母或特定缩写结尾的句子,如“Mr”,“Mrs”,“Ms”,“Ltd”,“etc”等。查询列表或制作您自己的列表。有些不确定 - 例如,是“Mass”。必然是一个国家的缩写? – 2010-07-25 14:57:55

+1

你试图解决什么问题导致你这么做?自然语言解析不适用于心灵的懦弱,所以如果你能更好地定义你的情况,你可能会得到更多有用的答案。 – Daenyth 2010-07-25 20:06:45

回答

10

忽略的考虑,如当.构成句子的结尾:

import re 
' '.join(re.split(r'(?<=[.?!])\s+', phrase, 2)[:-1]) 

编辑:刚刚发生,我的另一种方法是这样的:

re.match(r'(.*?[.?!](?:\s+.*?[.?!]){0,1})', phrase).group(1) 

注:

  1. 尽管第一个解决方案,您可以用一些其他数字替换2来选择不同的句子,在第二个解决方案,您在{0,1}改变1到一个小于号你想要提取的句子。
  2. 第二种解决方案在处理空间字符串或没有标点符号的字符串时不够健壮。可以这样做,但是正则表达式会比现在更复杂,并且我会赞成效率稍低的第一种解决方案,而不是一团糟。
+0

谢谢,这工作,但它返回一个列表。我尝试使用for循环并手动插入。回到一个字符串。除了没有?要么 !句子在我的字符串:) – anroots 2010-07-25 15:34:59

+0

如果'句子'是返回的列表,然后只是做'“。”.join(句子)'把它作为一个字符串 – aaronasterling 2010-07-25 17:51:25

+0

@aaronasterling:我已经修改我的答案保留标点符号并重新加入句子。 – 2010-07-25 23:45:00

1

我解决了这样的问题:Separating sentences,虽然对该帖子的评论也指向NLTK,但我不知道如何找到在其网站上句分割...

0

这里的哟怎么能做到这一点:

str = "Sentence one? Sentence two. Sentence three? Sentence four. Sentence five." 
sentences = str.split(".") 
allSentences = [] 
for sentence in sentences 
    allSentences.extend(sentence.split("?")) 

print allSentences[0:3] 

可能有更好的方法,我期待看到他们。

+0

啊,马塞洛的解决方案确实好多了。不知道有一个正则表达式分割函数。 – TimCinel 2010-07-25 14:03:12

0

这里是一步一步解释如何反汇编,选择前两句,并重新组装它。正如其他人所指出的,这并没有考虑到并非所有的点/问题/感叹号都是真正的句子分隔符。

import re 

testline = "Sentence 1. Sentence 2? Sentence 3! Sentence 4. Sentence 5." 

# split the first two sentences by the dot/question/exclamation. 
sentences = re.split('([.?!])', testline, 2) 
print "result of split: ", sentences 

# toss everything else (the last item in the list) 
firstTwo = sentences[:-1] 
print firstTwo 

# put the first two sentences back together 
finalLine = ''.join(firstTwo) 
print finalLine 
0

发电机替代使用我的效用函数返回的绳子,直到在搜索序列中的任何项目:

from itertools import islice 
testline = "Sentence 1. Sentence 2? Sentence 3! Sentence 4. Sentence 5." 
def multis(search_sequence,text,start=0): 
    """ multisearch by given search sequence values from text, starting from position start 
     yielding tuples of text before found item and found sequence item""" 
    x='' 
    for ch in text[start:]: 
     if ch in search_sequence: 
      if x: yield (x,ch) 
      else: yield ch 
      x='' 
     else: 
      x+=ch 
    else: 
     if x: yield x 

# split the first two sentences by the dot/question/exclamation. 
two_sentences = list(islice(multis('.?!',testline),2)) ## must save the result of generation 
print "result of split: ", two_sentences 

print '\n'.join(sentence.strip()+sep for sentence,sep in two_sentences)