首页 > 解决方案 > 从不属于单词的字符串列表中删除标点符号

问题描述

我正在编写一个程序来检测二元组的搭配(两个词一起出现的频率高于偶然,例如:热狗)。要正确执行此操作,我必须删除所有将作为自己的元素存储的标点符号,但保留作为单词一部分的标点符号。例如,二元组 ['US flag'] 应保留 US 中的句点,但 ['US ,'] 应删除逗号。我编写了一个 for 循环,它遍历标点符号列表并应该删除匹配的元素,但这并没有改变任何东西。此外,我使用正则表达式删除了大多数标点符号,但如果我删除句点,那么其中带有句点的单词也会被破坏。任何有关消除这些问题的有效方法的建议将不胜感激!

到目前为止,这是我的代码:

f = open('Collocations.txt').read()

punctuation = [',', '.', '!', '?', '"', ':', "'", ';', '@', '&', '$', '#', '*', '^', '%', '{', '}']
filteredf = re.sub(r'[,":@#?!&$%}{]', '', f)

f = f.split()

print(len(f))
for i, j in zip (punctuation, f):
    if i == j:
        ind = f.index(j)
        f.remove(f[ind])
print(len(f))


# removes first element in the temp list to prepare to make bigrams
temp = list()
temp2 = list()
temp  = filteredf.split()
temp2 = filteredf.split()
temp2.remove(temp2[0]) 

# forms a list of bigrams
bi = list()
for i, j in zip(temp, temp2):
    x = i + " " + j
    bi.append(x)
#print(len(bi))
unigrams = dict()
for i in temp:
    unigrams[i] = unigrams.get(i, 0) + 1 
#print(len(unigrams))



bigrams = dict()
for i in bi:
    bigrams[i] = bigrams.get(i, 0) + 1
#print(len(bigramenter code here`

标签: pythonnlp

解决方案


更换

for i, j in zip (punctuation, f):
    if i == j:
        ind = f.index(j)
        f.remove(f[ind])

while i < len(f)-2:
    c1 = f[i]
    c2 = f[i+1]
    c3 = f[i+2]
    if c2 in punctuation and not (c1 in string.ascii_letters and c3 in string.ascii_letters):
        f = f[:i+1] + f[i+2:]
    i+=1

将保留两边都有字母的标点符号(例如 USA 将成为 USA),但在我看来,无法区分最后一个句点和句号之间的区别,例如 USA.和 Hello.


推荐阅读