Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/list/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
比较列表的子项并在Python中进行更改_Python_List_Part Of Speech - Fatal编程技术网

比较列表的子项并在Python中进行更改

比较列表的子项并在Python中进行更改,python,list,part-of-speech,Python,List,Part Of Speech,我有两个来自词性标记的列表,如下所示: pos_tags = [('This', u'DT'), ('is', u'VBZ'), ('a', u'DT'), ('test', u'NN'), ('sentence', u'NN'), ('.', u'.'), ('My', u"''"), ('name', u'NN'), ('is', u'VBZ'), ('John', u'NNP'), ('Murphy', u'NNP'), ('and', u'CC'), ('I', u'PRP'), ('l

我有两个来自词性标记的列表,如下所示:

pos_tags = [('This', u'DT'), ('is', u'VBZ'), ('a', u'DT'), ('test', u'NN'), ('sentence', u'NN'), ('.', u'.'), ('My', u"''"), ('name', u'NN'), ('is', u'VBZ'), ('John', u'NNP'), ('Murphy', u'NNP'), ('and', u'CC'), ('I', u'PRP'), ('live', u'VBP'), ('happily', u'RB'), ('on', u'IN'), ('Planet', u'JJ'), ('Earth', u'JJ'), ('!', u'.')]


pos_names = [('John', 'NNP'), ('Murphy', 'NNP')]

我想创建一个最终列表,用pos_名称中的列表项更新pos_标记。因此,基本上我需要在pos_标记中找到John和Murphy,并将pos标记替换为NNP。

您可以从
pos_名称创建一个字典,其行为类似于查找表。然后,您可以使用
get
在表中搜索可能的替换项,如果没有找到替换项,则保持标记不变

d = dict(pos_names)
pos_tags = [(word, d.get(word, tag)) for word, tag in pos_tags]
给定

你可以做:

[next((subl for subl in pos_tags if name in subl)) for name in names]
这将给你:

[('John', u'NNP'), ('Murphy', u'NNP')]

我同意字典是解决这个问题的更自然的方法,但是如果你需要你的
pos\u标签
,一个更明确的方法是:

for word, pos in pos_names:
    for i, (tagged_word, tagged_pos) in enumerate(pos_tags):
        if word == tagged_word:
            pos_tags[i] = (word,pos)

(一个字典对于大量单词来说可能更快,所以你可能需要考虑把单词顺序存储在一个列表中,并使用字典进行POS分配)。

到<代码> [(行星',u'jj'),(‘地球’,u'jj')]
property?到目前为止你试过什么吗?这是一个复制粘贴错误,现在已在原始帖子中更正。John和Murphy已经在你的
pos\u标签列表中与NNP关联。你能再举一个例子吗?如果看到新的pos标记,是否要更改pos标记?我尝试了一些嵌套循环,但没有成功。与其说我是一名程序员,不如说我是一名语言学家,所以这一切都有点让人难以接受。干杯。但是我的列表是这样的:name=[('John','NNP'),('Murphy','NNP')]完美。我不太担心性能,所以这对我来说很好。
[('John', u'NNP'), ('Murphy', u'NNP')]
for word, pos in pos_names:
    for i, (tagged_word, tagged_pos) in enumerate(pos_tags):
        if word == tagged_word:
            pos_tags[i] = (word,pos)