删除单引号同时保留撇号Python,NLTK

2024-06-01 12:46:46 发布

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

我正试图建立一个诗歌语料库的频率列表。代码读取.txt文件并用数据创建一个.csv。

我正在努力的部分是去掉文本中不相关的标点符号。我目前掌握的相关代码是:

import nltk

raw = open('file_name.txt', 'r').read()
output = open('output_filename.csv','w')
txt = raw.lower()

pattern = r'''(?x)([A_Z]\.)+|\w+(-\w+)*|\.\.\|[][.,;"'?():-_`]'''
tokenized = nltk.regexp_tokenize(txt,pattern)

这几乎是完美的工作,因为它保留了单词中的连字符,例如烟囱清洁工,但它也将收缩分成两个独立的单词,这不是我想要的。

例如,我的文本文件(试运行是在威廉·布莱克的《纯真之歌》上)有这样几行:

'Pipe a song about a Lamb!'

我想成为

Pipe | a | song | about | a | Lamb

我之前使用的代码保持了缩略词的完整性,但也给我留下了一个引号:

for punct in string.punctuation:
    txt = txt.replace(punct,' ')
re.sub(r'\r+',' ',txt)

所以我会得到

'Pipe | a | song | about | a | Lamb

我想在这两者之间找到一个中间点,因为我需要在诸如O'er和连字符之类的单词中保留撇号,但要去掉其他所有东西。

我知道这个话题在这个论坛上似乎已经穷尽了,但是我花了四天的时间尝试每一个提供的例子,却没能让他们按照广告的方式工作,所以我不想把头发都扯出来,我想我应该试着发布一个问题。

编辑:

似乎标准的标记器不能处理我的文本的原因是一些撇号在奇怪的地方偏左偏右。我使用了一堆.replace()指令生成了所需的结果:

txt = txt.replace("\n", " ")
#formats the text so that the line break counts as a space
txt = txt.replace("”", " ")
#replaces stray quotation marks with a space
txt = txt.replace("“", " ")
#replaces stray quotation marks with a space
txt = txt.replace(" ’", " ")
#replaces a right leaning apostrophe with a space if it follows a space(which now includes line breaks)
txt = txt.replace(" ‘", " ")
#replaces a left leaning apostrophe with a space if it follows a space

我毫不怀疑有一种方法可以将所有这些代码合并成一行代码,但我真的很高兴它都能工作!


Tags: csv代码文本txtrawsongwithspace
1条回答
网友
1楼 · 发布于 2024-06-01 12:46:46

与其替换标点符号,不如在空格上split,然后在每个单词的开头和结尾处strip使用标点符号:

>>> import string
>>> phrase = "'This has punctuation, and it's hard to remove!'"
>>> [word.strip(string.punctuation) for word in phrase.split(" ")]
['This', 'has', 'punctuation', 'and', "it's", 'hard', 'to', 'remove']

这将在单词中保留撇号和连字符,同时删除单词开头或结尾的标点符号。


请注意,独立标点将被空字符串""替换:

>>> phrase = "This is - no doubt - punctuated"
>>> [word.strip(string.punctuation) for word in phrase.split(" ")]
['This', 'is', '', 'no', 'doubt', '', 'punctuated']

这很容易过滤掉,因为空字符串的计算结果是False

filtered = [f for f in txt if f and f.lower() not in stopwords]
                            # ^ excludes empty string

相关问题 更多 >