【问题标题】:Need help for ValueError: substring not foundValueError 需要帮助:找不到子字符串
【发布时间】:2020-05-15 07:06:16
【问题描述】:

我想把句子写成如下:

(N(Hace calor.)-(S(De todas formas, no salgo a casa.)))

(N(Además, va a venir Peter.)-(S(Sin embargo, no lo sé a qué hora llegará exactamente.)))

但是程序只能给我第一句话并给出一个错误为 ValueError: substring not found for the second sentence。任何人都可以帮忙吗?谢谢!

这是我的代码:

from nltk import tokenize
sent = 'Hace calor. De todas formas, no salgo a casa. Además, va a venir Peter. Sin embargo, no lo sé a qué hora llegará exactamente.'
Ant = ['De todas formas', 'Sin embargo']
sent = tokenize.sent_tokenize(sent)
for i in sent:
    for DMAnt in Ant:
        if DMAnt in i:
            sent = '(N(' + str(sent[sent.index(i)-1]) + ')-Antithesis-' +'(S(' + str(sent[sent.index(i)]) + '))'
    print(sent)

【问题讨论】:

  • sent_tokenize() 返回一个列表。但是你在循环中将它改回赋值中的字符串。
  • 所以在下一次迭代中,sent.index(i) 将不起作用,因为sent 是一个字符串而不是句子列表。
  • 也许你只需要使用不同的变量。
  • 好的,谢谢!我认为这是个好主意。

标签: python nltk valueerror


【解决方案1】:

您正在更改您的sent。我建议创建一个新变量,它会解决问题。

import nltk
nltk.download('punkt')
from nltk import tokenize
sent = 'Hace calor. De todas formas, no salgo a casa. Además, va a venir Peter. Sin embargo, no lo sé a qué hora llegará exactamente.'
Ant = ['De todas formas', 'Sin embargo']
sent = tokenize.sent_tokenize(sent)
new=[]
for i in sent:
    for DMAnt in Ant:
        if DMAnt in i:
            new.append('(N(' + str(sent[sent.index(i)-1]) + ')-Antithesis-' +'(S(' + str(sent[sent.index(i)]) + '))')

print(new)   

输出:

['(N(Hace calor.)-Antithesis-(S(De todas formas, no salgo a casa.))', '(N(Además, va a venir Peter.)-Antithesis-(S(Sin embargo, no lo sé a qué hora llegará exactamente.))']

new 变量将以列表的形式获得您想要的输出。

【讨论】:

  • 我认为这是我想要得到的一个好主意。非常感谢!
  • 不错。嗨,如果这个答案解决了您的问题,您能否通过单击其侧面的复选标记将其标记为已接受?谢谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-09-08
  • 2014-10-04
  • 1970-01-01
  • 1970-01-01
  • 2018-10-09
  • 1970-01-01
  • 2015-01-30
相关资源
最近更新 更多