从不属于单词的字符串列表中删除标点符号

2024-06-26 18:00:28 发布

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

我正在写一个程序来检测bigrams的搭配(两个词经常出现在一起,而不是偶然出现,例如:hotdog)。为了做到这一点,我必须删除所有的标点符号,将存储为自己的元素,但保留标点符号是一个词的一部分。例如,bigram['U.S.flag']应该保持句点为U.S.,但是['U.S.,']应该删除逗号。我编写了一个for循环,循环遍历标点符号列表,应该删除匹配的元素,但这不会改变任何东西。另外,我用regex删除了大多数标点符号,但是如果我删除了句点,那么带有句点的单词也会被破坏。任何有效的方法来消除这些建议将不胜感激

以下是我目前的代码:

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`

Tags: in元素forlentemplistsplitprint
1条回答
网友
1楼 · 发布于 2024-06-26 18:00:28

更换

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

将保留两边都有字母的标点符号(例如,U.S.a.将成为U.S.a),但是在我看来,不可能区分句号和句号之间的区别,例如U.S.a.和Hello.

相关问题 更多 >