首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >用断线和解析隔开句子。

用断线和解析隔开句子。
EN

Stack Overflow用户
提问于 2014-04-16 10:42:53
回答 2查看 90关注 0票数 1

考虑到我已经用一个分行符分隔了标记语句,并且我有两个列表示标记的实际和预测标记。我想遍历每一个标记,找出错误的预测,例如实际的标记不等于预测的标记。

代码语言:javascript
复制
#word actual predicted

James PERSON PERSON
Washington PERSON LOCATION     
went O O
home O LOCATION

He O O
took O O
Elsie PERSON PERSON
along O O

>James Washington went home: Incorrect
>He took Elsie along: Correct
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2014-04-16 11:18:59

除了我的previous answer之外,我还在这里使用all()和列表理解:

代码语言:javascript
复制
from itertools import groupby

d = {True: 'Correct', False: 'Incorrect'}
with open('text1.txt') as f:
    for k, g in groupby(f, key=str.isspace):
        if not k:
            # Split each line in the current group at whitespaces
            data = [line.split() for line in g] 
            # If for each line the second column is equal to third then `all()` will
            # return True.
            predicts_matched = all(line[1] == line[2] for line in data)
            print ('{}: {}'.format(' '.join(x[0] for x in data), d[predicts_matched]))

输出:

代码语言:javascript
复制
James Washington went home: Incorrect
He took Elsie along: Correct
票数 0
EN

Stack Overflow用户

发布于 2014-04-16 11:00:59

Python字符串具有强大的解析功能,您可以在这里使用。我使用Python3.3完成了这个操作,但是它也应该适用于任何其他版本。

代码语言:javascript
复制
thistext = '''James PERSON PERSON
Washington PERSON LOCATION     
went O O
home O LOCATION

He O O
took O O
Elsie PERSON PERSON
along O O
'''

def check_text(text):
    lines = text.split('\n')
    correct = [True] #a bool wrapped in a list,we can modify it from a nested function
    words = []

    def print_result():
        if words:
            print( ' '.join(words), ": ", "Correct" if correct[0] else "Incorrect" )
        #words.clear()
        del words[:]        
        correct[0] = True

    for line in lines:
        if line.strip():  # check if the line is empty
            word, a, b = line.split()
            if a != b:
                correct[0] = False
            words.append(word)
        else:
            print_result();

    print_result()

check_text(thistext)
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/23107142

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档