句子分裂的基本编号?

时间:2012-09-30 11:54:00

标签: python xml

  

可能重复:
  Numbering the sentences inside a <P> in a .xml file?

我刚开始编程,所以这个问题非常简单,除了我。我有一个包含以下内容的.xml文件:

<p> sentence1. sentence2. sentence3.</p>
<p> sentence1. </p>

现在我已经用BeautifulSoup编写了一个脚本来附加以STRING结尾的每个段落,所以它看起来像:

<p> sentence1. sentence2. sentence3. STRING</p>
<p> sentence1. STRING </p>

&lt; p>只包含一个我想做的句子。但是如果&lt; p>包含超过我的句子,我想将STRING添加到每个句子结尾+句子编号。例如,上段是:

<p> sentence1. STRING1 sentence2. STRING2 sentence3. STRING3 </p>

这是我使用.append方法的1个句子的工作脚本,但我无法让它用于多个句子。任何帮助将不胜感激!

soup = BeautifulSoup(xmlfile)
p = norm.findAll("p")

for i in p:
    dotsplit = re.compile(r'\. \w')
    sentences = dotsplit.split(i.text)

    if len(sentences) == 1:
        appendix = "STRING"
        i.append(appendix)
        print i

    if len(sentences) > 1:
        for x in sentences:
            sentencenumber = ???????  
            # Should equal (index of sentences)+1,  meaning sentences[0] = 1
            appendix = sentencenumber + "STRING"
            i.append(appendix)
            print i

2 个答案:

答案 0 :(得分:1)

这应该足够了:

if len(sentences) > 1:
    for n, x in enumerate(sentences):
        sentencenumber = n + 1

答案 1 :(得分:1)

如果我理解正确的话:

if len(sentences) == 1:
    print sentences[0] + 'STRING'
elif len(sentences) > 1:
    isentences = ('%s%s%d' % (s, 'STRING', i) for i, s in enumerate(sentences, 1))
    print ' '.join(isentences)
  

我不知道如何在每个句子之后追加它

BeautifulSoup文档说你必须使用方法tag.string.replace_with而不是tag.append:

    isentences = ('%s%s%d' % (s, 'STRING', i) for i, s in enumerate(sentences, 1))
    i.string.replace_with(' '.join(isentences))