加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

停止在python中打印“无匹配”的一致性

发布时间:2020-12-20 13:48:48 所属栏目:Python 来源:网络整理
导读:我正在对列表中的每个项目应用一致性命令.它工作正常,但是当它找不到匹配时,它打印出不匹配.我希望它忽略这些并且只打印匹配的结果. absol是包含列表的变量 以下是脚本的相关部分: def get_all_phrases_containing_tar_wrd(target_word,tar_passage,left_ma
我正在对列表中的每个项目应用一致性命令.它工作正常,但是当它找不到匹配时,它打印出不匹配.我希望它忽略这些并且只打印匹配的结果.

absol是包含列表的变量

以下是脚本的相关部分:

def get_all_phrases_containing_tar_wrd(target_word,tar_passage,left_margin = 10,right_margin = 10):
    Ellis = nltk.word_tokenize(tar_passage)
    text = nltk.Text(Ellis)
    c = nltk.ConcordanceIndex(text.Ellis,key = lambda s: s.lower())
    concordance_txt = ([text.Ellis[map(lambda x: x-5 if (x-left_margin)&gt[0] else 0,[offset])[0]:offset+right_margin]
                    for offset in c.offsets(target_word)])
    return [''.join([x+' ' for x in con_sub]) for con_sub in concordance_txt]

Ellis = nltk.word_tokenize(raw)
text = nltk.Text(Ellis)
for t_word in absol:
    text.concordance(t_word)
print
print 'Results from function'
results = get_all_phrases_containing_tar_wrd(absol,raw)
for result in results:
    print result

解决方法

在你的程序中,你有以下几行:

text = nltk.Text(Ellis)
for t_word in absol:
    text.concordance(t_word)

您可以使用以下代码替换这些行:

ci = nltk.ConcordanceIndex(Ellis)
for t_word in absol:
    if ci.offsets(t_word):
        ci.print_concordance(t_word)

额外的if会导致脚本忽略它无法匹配的项目.请注意,您必须从使用Text对象切换到更具体的ConcordanceIndex对象.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读