Python列表元组元素替换求助:将词性为NN的词替换为'NN'
Solution for Replacing Words with 'NN' Where POS Tag is 'NN'
Hey there! I've got you covered. The key here is to iterate through each tuple in your list, check if the part-of-speech (POS) tag is NN, and replace the corresponding word with NN when that condition is met.
Using List Comprehension (Concise, Pythonic Approach)
This is the most efficient way to handle this task—it's short and easy to read once you're familiar with list comprehensions:
# Your original data list original_data = [('The', 'NNP'), ('map', 'NNP'), ('is', 'VBZ'), ('way', 'NN'), ('of', 'IN'), ('using', 'VBG'), ('tool', 'NN'), (',', ','), ('skill', 'VBG'), ('and', 'CC')] # Modify the list with conditional logic in a comprehension modified_data = [('NN', pos) if pos == 'NN' else (word, pos) for word, pos in original_data] # Print the final result print(modified_data)
Using a For Loop (Beginner-Friendly, Explicit Approach)
If you prefer to break down each step for clarity, a basic for loop works just as well:
original_data = [('The', 'NNP'), ('map', 'NNP'), ('is', 'VBZ'), ('way', 'NN'), ('of', 'IN'), ('using', 'VBG'), ('tool', 'NN'), (',', ','), ('skill', 'VBG'), ('and', 'CC')] modified_data = [] for word, pos in original_data: # Check if the POS tag matches 'NN' if pos == 'NN': modified_data.append(('NN', pos)) else: # Keep the original tuple unchanged modified_data.append((word, pos)) print(modified_data)
Expected Output
Both methods will generate exactly the output you need:
[('The', 'NNP'), ('map', 'NNP'), ('is', 'VBZ'), ('NN', 'NN'), ('of', 'IN'), ('using', 'VBG'), ('NN', 'NN'), (',', ','), ('skill', 'VBG'), ('and', 'CC')]
内容的提问来源于stack exchange,提问作者Steve DEU
相关产品推荐
相关产品推荐

