Python:标准化文本文件

2 投票
2 回答
3196 浏览
提问于 2025-04-17 02:00

我有一个文本文件,里面包含了很多单词的不同拼写方式:

比如:

identification ... ID .. identity...contract.... contr.... contractor...medicine...pills..tables

所以我想要一个同义词文本文件,里面包含这些单词的同义词,并希望把所有的变体替换成主要的单词。简单来说,我想把输入文件的内容规范化。

比如,我的同义词列表文件看起来会是这样的:

identification = ID identify
contracting = contract contractor contractors contra...... 
word3 = word3_1 word3_2 word3_3 ..... word3_n
.
.
.
.
medicine = pills tables drugs...

我希望最终输出的文件看起来是这样的:

identification ... identification .. identification...contractor.... contractor.... contractor...medicine...medicine..medicine

我该如何用Python编程呢?

非常感谢你的帮助!!!

2 个回答

3

我只是想说一句:与其列出一个词的所有变体,不如看看difflib这个工具。

>>> get_close_matches('appel', ['ape', 'apple', 'peach', 'puppy'])
['apple', 'ape']
>>> import keyword
>>> get_close_matches('wheel', keyword.kwlist)
['while']
>>> get_close_matches('apple', keyword.kwlist)
[]
>>> get_close_matches('accept', keyword.kwlist)
['except']
3

你可以先读取同义词文件,然后把它转换成一个字典,叫做 table

import re

table={}
with open('synonyms','r') as syn:
    for line in syn:
        match=re.match(r'(\w+)\s+=\s+(.+)',line)
        if match:
            primary,synonyms=match.groups()
            synonyms=[synonym.lower() for synonym in synonyms.split()]
            for synonym in synonyms:
                table[synonym]=primary.lower()

print(table)

这样就得到了

{'word3_1': 'word3', 'word3_3': 'word3', 'word3_2': 'word3', 'contr': 'contracting', 'contract': 'contracting', 'contractor': 'contracting', 'contra': 'contracting', 'identify': 'identification', 'contractors': 'contracting', 'word3_n': 'word3', 'ID': 'identification'}

接下来,你可以读取文本文件,把每个单词用它在 table 中的主要同义词替换掉:

with open('textfile','r') as f:
    for line in f:
        print(''.join(table.get(word.lower(),word) 
                      for word in re.findall(r'(\W+|\w+)',line)))

这样就得到了

identification     identification    identity   contracting     contracting     contracting   medicine   medicine  medicine

  1. re.findall(r'(\w+|\W+)',line) 用来分割每一行,同时保留空格。如果空格不重要,你也可以用更简单的 line.split()
  2. table.get(word,word) 会返回 table[word],如果这个单词在 table 里;如果不在,就直接返回 word

撰写回答