Python 从NLTK中的令牌中删除URL功能

Python 从NLTK中的令牌中删除URL功能,python,django,python-2.7,twitter,nltk,Python,Django,Python 2.7,Twitter,Nltk,我正在构建一个小的“趋势”算法。tokeniser的工作原理与最初的预期一致,它阻止了URL周围的几个小问题,这导致了一些问题 显然,当我从推特上获取信息时,有很多t.co URL短链接类型的链接。我想删除这些不是“文字”,最好是在tokeniser阶段,但目前正在将它们过滤掉。我不能(我不认为)在一个可识别的英语白名单上运行代币,同样,Twitter和缩写等等 我的代码围绕着在任何给定时间段内提取前10个最常见单词的函数: tweets = Tweet.objects.filter(lang=

我正在构建一个小的“趋势”算法。tokeniser的工作原理与最初的预期一致,它阻止了URL周围的几个小问题,这导致了一些问题

显然,当我从推特上获取信息时,有很多t.co URL短链接类型的链接。我想删除这些不是“文字”,最好是在tokeniser阶段,但目前正在将它们过滤掉。我不能(我不认为)在一个可识别的英语白名单上运行代币,同样,Twitter和缩写等等

我的代码围绕着在任何给定时间段内提取前10个最常见单词的函数:

tweets = Tweet.objects.filter(lang='en', created_at__gte=start, created_at__lte=end)
number_of_tweets = tweets.count()
most_popular = trending.run_all(start, end, "word").keys()[:10]
print "BEFORE", most_popular
for i, thing in enumerate(most_popular):
    try:
        if "/" in thing:
            most_popular.remove(thing)
            print i, thing, "Removed it."
    except UnicodeEncodeError, e:
        print "Unicode error", e
        most_popular.remove(thing)
print "NOW", most_popular`
理论上,try/except块应该从令牌列表中删除任何具有URL特征的单词——除非没有,否则我总是会留下一些

在一个时间段内运行trending.run_all,例如:

[u'//t.co/r6gkL104ai/nKate',
你“解释”,
u'\U0001f62b\U0001f62d/nRT',
u'woods',
"吊",,
u'ndtv/nRT',
u'BenDohertyCorro',
u'\u0928\u093f\u0930\u094d\u0926\u094b\u0937\u092c\u093e\u092a\u0942\u2026/nPolice',
“最后一个”,
u'health/nTime']

运行导入python命令行的其余代码可以提供:

0 //t.co/r6gkL104ai/nKate Removed it
1 It seems to me that the issue you are having is that you are deleting a list while iterating over it. The solution is simple:
You should iterate on a copy of your list:

for i, thing in enumerate(most_popular[:]):
0//t.co/r6gkL104ai/nKate将其删除

1在我看来,您遇到的问题是,您在迭代列表时正在删除列表。解决方案很简单: 您应该在列表的副本上迭代:

请注意“[:]”,它将创建列表的副本


这种行为的原因可以在下面找到。

第一行应该是:
对于i,枚举中的东西(最流行的[:]):
-这现在会抛出一个不同的
错误列表。删除(x):x不在列表中,这表明这还不是正确的答案。您需要“枚举”对象吗?你可以在列表上迭代而不使用它。你是对的,我只是出于调试的目的,它仍然抛出x not in list错误。你能检查/打印列表中的哪个元素产生了这个错误吗?我最终要做的是:
对于最流行的[:]中的东西:try:if/“在thing:most\u popular.remove(thing)print thing,“remove it.”在thing:most\u popular.remove(thing)print thing.remove(thing)print thing“remove it.”除UnicodeEncodeError外,e:try:most\u popular.remove(thing)除值错误:除值错误外通过:通过
(呃,注释中的格式)