使用Python和NLTK,我编写了一个正则表达式来查找正文中以大写字母开头但不在句子开头的单词。
最初,我按如下方式使用它:
[w for w in text if re.findall(r'(?<!\.\s)\b[A-Z][a-z]\b',w)]变量文本是使用树库语料库创建的,如下所示:
>>> def concat(lists):
biglist = [ ]
while len(lists)>0:
biglist = biglist+lists[0]
lists=lists[1:]
return biglist
>>> tbsents = concat(treebank.sents()[200:250])
>>> text = nltk.Text(tbsents)然而,这似乎不起作用,它仍然返回句子开头的单词。所以我想我应该尝试使用text.findall()函数。我运行以下命令,它会根据需要返回所有大写字母的单词。
>>> text.findall("<[A-Z][a-z]{3,}>")我的问题是,我不知道如何将正则表达式的第一位转换为第二个函数所需的<..>格式,如果我这样做了,它会工作吗,或者我采取了完全错误的方法?
谢谢。
发布于 2012-01-06 04:30:35
我不确定您对第一个列表理解做了什么:您在每个单词上使用findall,而不是在文本本身上。
对treebank语料库执行您想要的操作的最简单方法是:
import itertools
non_starting_words = list(itertools.chain(*[s[1:] for s in treebank.sents()]))
uppercase_words = [w for w in non_starting_words if w[0].isupper()]也许这就是你想用"concat“函数做的事情,但它只得到了一个所有单词的列表--它没有删除每个句子的第一个单词。如果您确实想要连接列表列表,一种更好的方法是我上面做的list(itertools.chain(* lists ))方法。
ETA:假设您必须使用一系列令牌,那么最好的解决方案就是不使用正则表达式,而是使用:
punctuation_marks = ".!?"
first_word = True
uppercase_words = []
for w in text:
if not first_word and re.match("[A-Z][a-z]*$", w):
uppercase_words.append(w)
first_word = w in punctuation_marks
print uppercase_wordshttps://stackoverflow.com/questions/8748870
复制相似问题