如何迭代fi中的元组

2024-05-16 23:24:28 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在为我的NLP类做一个项目,现在我有一个.txt文件,看起来像这样:

(u'I', u'PRON')(u'am', u'VERB')(u'nobody', u'NOUN')(u':', u'.')(u'A', u'DET')(u'red', u'ADJ')(u'sinking', u'NOUN')(u'autumn', u'NOUN')(u'sun', u'NOUN')(u'Took', u'NOUN')(u'my', u'PRON')(u'name', u'NOUN')(u'away', u'ADV')(u'.', u'.')(u'Keep', u'VERB')(u'straight', u'VERB')(u'down', u'PRT')(u'this', u'DET')(u'block', u'NOUN')....

所以基本上,它只是一堆带单词和标签的元组。我试着遍历这个文件并返回一个列表,上面只标记了“NOUN”

因此,输出可能如下:["nobody," "autumn",....]

我真的不确定如何遍历这些元组,所以要去掉u'tag。有人能帮忙吗?你知道吗


Tags: 文件项目txtnlpredam元组noun
3条回答

您可以使用列表理解来执行此操作,例如:

lst = [i[0] for i in tuples if i[1] == "NOUN"]

列表理解语法有点混乱,所以这里是循环的等价形式

lst=[]
for i in tuples:
    if i[1] == "NOUN":
        lst.append(i)

使用列表理解来分解所有元组,对单词应用str函数将其转换为字符串而不是unicode,并根据单词的类型筛选出单词:

output=[str(word) for word,wtype in tuplist if wtype.lower()=='noun']

一个小技巧是使用lower函数来标准化字符串以检查条件。如果你认为你会有流氓空格,你也可以使用strip(),就像: wtype.lower().strip()=='noun'

考虑到您在文本文件中有数据,下面是一个使用regex的解决方案:

import re
data = """(u'I', u'PRON')(u'am', u'VERB')(u'nobody', u'NOUN')(u':', u'.')(u'A', u'DET')(u'red', u'ADJ')(u'sinking', u'NOUN')(u'autumn', u'NOUN')(u'sun', u'NOUN')(u'Took',u'NOUN')(u'my', u'PRON')(u'name', u'NOUN')(u'away', u'ADV')(u'.', u'.')(u'Keep', u'VERB')(u'straight', u'VERB')(u'down', u'PRT')(u'this',u'DET')(u'block', u'NOUN')'s = r"(u'I', u'PRON')(u'am', u'VERB')(u'nobody', u'NOUN')(u':', u'.')(u'A', u'DET')(u'red', u'ADJ')(u'sinking', u'NOUN')(u'autumn', u'NOUN')(u'sun', u'NOUN')(u'Took', u'NOUN')(u'my', u'PRON')(u'name', u'NOUN')(u'away', u'ADV')(u'.', u'.')(u'Keep', u'VERB')(u'straight',u'VERB')(u'down', u'PRT')(u'this', u'DET')(u'block', u'NOUN')"""
#Use regex to get the split the data as required
rx = re.compile(r"\(u'(.*?)'\,\su'(.*?)'\)")
#Find all the matches
matches = rx.findall(s)
tuples = []
for match in matches:
    tuples.append(match)

#Get the nouns from the list of tuples  
nouns = [ x for x in tuples if "NOUN" in x]

下图显示了生成的结果: enter image description here

相关问题 更多 >