python - 从不属于单词的字符串列表中删除标点符号
问题描述
我正在编写一个程序来检测二元组的搭配(两个词一起出现的频率高于偶然,例如:热狗)。要正确执行此操作,我必须删除所有将作为自己的元素存储的标点符号,但保留作为单词一部分的标点符号。例如,二元组 ['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`
解决方案
更换
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.
推荐阅读
- java - 如何在此处完成加法以及检测结果无法表示的有效方法
- python - 在 Pandas 中分配组的第一行
- analytics - Microsoft AppCenter-活跃用户和顶级设备中的用户数量有什么区别?
- sql-server - 将xml文件导入sql server表而不进行bulkcopy
- javascript - 使用 Nightwatch 编写异步自定义命令
- python - 如何将新文件保存到其他目录
- c# - JQuery Datatables 在所有可用页面上获取所有“选中”复选框
- javascript - 如何使用firebase使用手机登录?我收到此错误消息“”reCAPTCHA 容器未找到或已包含内部元素!”
- node.js - 由于错误的构建脚本,无法将 node.js + react.js 应用程序部署到 Heroku
- java - Spring批处理文件读取:JBOSS EAP 6.2文件编码从UTF-8到ISO-8859-1