Python:替换项目

标签 python string replace nltk

我有以下内容:

[('The', 'NNP'), ('map', 'NNP'), ('is', 'VBZ'), 
('way', 'NN'), ('of', 'IN'), ('using', 'VBG'), ('tool', 'NN'), 
(',', ','), ('skill', 'VBG'), ('and', 'CC')]

而且,每次与“NN”配对时,我都需要将字符串替换为“NN”。所以输出应该是:

[('The', 'NNP'), ('map', 'NNP'), ('is', 'VBZ'), 
('NN', 'NN'), ('of', 'IN'), ('using', 'VBG'), ('NN', 'NN'), 
(',', ','), ('skill', 'VBG'), ('and', 'CC')]

我尝试了以下操作,但它不会替换该项目。请帮忙!

for s in sentence:
    if s[1] == 'NN':
        s[0] == 'NN'
print(sentence)

最佳答案

元组不能被分配——它们是不可变的。一种选择是从头开始重新构建 POS 标签列表。

pos_tags = [(x if y != 'NN' else y, y) for x, y in pos_tags] 

如果不是这样,那么,重新分配您的列表项。

for i, (x, y) in enumerate(pos_tags):
    if y == 'NN':
        pos_tags[i] = ('NN', 'NN')

print(pos_tags)

[('A', 'NNP'),
 ('Discourse', 'NNP'),
 ('is', 'VBZ'),
 ('NN', 'NN'),
 ('of', 'IN'),
 ('using', 'VBG'),
 ('NN', 'NN'),
 (',', ','),
 ('thinking', 'VBG'),
 ('and', 'CC'),
 ('acting', 'VBG')]

关于Python:替换项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49951647/

相关文章:

c - 大字符串 C/C++ 的优化

string - 如何删除不可打印的字符

hadoop - 将 HIVE 查询结果中的空值或 NULL 值替换为特定值

python - 替换字符串中的日期时间字符

python - 使用 pandas 修改捕获组

python - Pandas 和 HDF5 中的文件大小减小

python - 生成随机数据以通过假设测试 pandas 数据框

python - 为什么 Pandas DataFrame Resample 会更改列顺序

python - 导入错误 : cannot import name normalize

java - 字符串数组中的错误 indexOf