如何在python使用lemas列表

2024-09-28 22:34:01 发布

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

a有问题: 我用python来分析数据。首先我使用引理列表(lemas.txt文件)对我的数据进行预处理。 我有引理列表: 例如:

A-bomb -> A-bombs
abacus -> abacuses
abandon -> abandons,abandoning,abandoned
abase -> abases,abasing,abased
abate -> abates,abating,abated
abbess -> abbesses
abbey -> abbeys
abbot -> abbots

。。。。。 你能帮我用我的列表来清除我的数据吗Python。谢谢你知道吗


Tags: 文件数据txt列表abacusbombbombsabandon
1条回答
网友
1楼 · 发布于 2024-09-28 22:34:01

这段代码将解析引理文件并将它们放入dict中,其中键是将被替换的单词,值是将被替换的单词。你知道吗

def parse_lemmas(leema_lines):
    for line in lemmas_lines:
        target, from_words_str = line.split(' -> ')
        from_words = from_words_str.split(',')
        for word in from_words:
            yield (word, target)


with open('lemmas.txt', 'r') as lemmas_file:
    lemmas = dict(parse_lemmas(lemma_line.strip() for lemma_line in lemmas_file))

# The dictionary lemmas now has all the lemmas in the lemmas file

一旦您将数据分割成一个单词列表,就可以运行以下代码。你知道吗

# if your data isn't too large
new_data = [lemmas.get(word, word) for word in data]

# if it's so large you don't want to make another copy,
# you can do it in-place
for idx, word in data:
    data[idx] = lemmas.get(word, word)

请注意,数据不必只是单词;例如,可以将"This is your data. This, here, is your data with punctuation; see?"拆分为['This', 'is', 'your', 'data', '.', 'This', ',', 'here', ',', 'is', 'your', 'data', 'with', 'punctuation', ';', 'see', '?']。在这种情况下,标点符号只会被传递出去。最好的方法取决于实际数据以及拆分/重新组合时需要保留哪些信息。你知道吗

相关问题 更多 >