分词结果不一致

人工智能 2026-07-09

我在用Python从文本数据中构建一组二元组(bigrams)。我也想把标点符号作为词元一并处理。下面是我的代码:

def get_all_bigrams():
    data = ""
    with open("data.txt", "r") as dataset:
        data = dataset.read()

    puncs: list = find_all_punctuations(data)
    print("".join(puncs)) # Output: `)*='[,-/:(&;]"!?.

    data = data.split()
    data = [str.lower(d) for d in data]
    print("Before punctuation separation:   ", len(data), "tokens")

    # Separate punctuations into a separate string
    separated_puncs = []
    for d in data:
        puncd = False
        for p in puncs:
            if p in d:
                parted = d.partition(p)
                if parted[0] != '':
                    separated_puncs.append(parted[0])
                if parted[1] != '':
                    separated_puncs.append(parted[1])
                if parted[2] != '':
                    separated_puncs.append(parted[2])
                puncd = True
                break
        if not puncd:
            separated_puncs.append(d)
    print("After punctuation separation:    ", len(separated_puncs), "tokens")

下面是我的不一致结果:

# Iteration 1
Before punctuation separation:    992315 tokens
After punctuation separation:     1124139 tokens
# Iteration 2
Before punctuation separation:    992315 tokens
After punctuation separation:     1123467 tokens
# Iteration 3
Before punctuation separation:    992315 tokens
After punctuation separation:     1123831 tokens

我做了一点调查,把迭代输出保存到了 txt 文件中,感到有点困惑:

# 1.txt
54172    ta
54173    '
54174    kul,
# 2.txt
54172    ta'kul
54173    ,

在对标点符号进行分割后,为什么会得到不一致的词元数量?

我记得读到过关于Python列表在每次执行脚本时会返回随机顺序的说法。这里也是这样吗?

下面是函数 find_all_punctuations 的定义,正如被采纳的回答者所指出的那样,它是造成不一致的根源。

def find_all_punctuations(text):
    all_punc = [char for char in text if char in string.punctuation]

    unique_punc = list(set(all_punc))

    return unique_punc

解决方案

问题在于 str.partition() 仅在找到第一个标点符号时就分割字符串。
如果一个词元包含多个标点符号,剩余的标点符号没有被正确分离。

示例:

"hello!!!"

将变成

["hello", "!", "!!"]

而不是:

["hello", "!", "!", "!"]

请使用正则表达式(re.findall)或逐字符分词,以将所有标点符号正确分离为独立的词元。

站内所有文章版权归属LeftHeroAI导航站,无授权禁止任何主体转载、抄袭、复制内容,亦不得私自架设镜像站点。一经侵权,本站将通过法律途径追责。

相关文章