Skip to main content
 首页 » 编程设计

Python正则表达式nltk网站提取

2024年08月30日33zhwl

您好,我以前从未处理过正则表达式,我正在尝试使用 Python 和 NLTK 预处理一些原始文本。 当我尝试使用以下方式标记文档时:

tokens = nltk.regexp_tokenize(corpus, sentence_re) 
sentence_re = r'''(?x)  # set flag to allow verbose regexps 
  ([A-Z])(\.[A-Z])+\.?  # abbreviations, e.g. U.S.A. 
| \w+(-\w+)*            # words with optional internal hyphens 
| \$?\d+(\.\d+)?%?      # currency and percentages, e.g. $12.40, 82% 
| \#?\w+|\@?\w+         # hashtags and @ signs 
| \.\.\.                # ellipsis 
| [][.,;"'?()-_`]       # these are separate tokens 
| ?:http://|www.)[^"\' ]+ # websites 
''' 

它不能将所有网站作为一个单一标记:

print toks[:50] 
['on', '#Seamonkey', '(', 'SM', ')', '-', 'I', 'had', 'a', 'short', 'chirp',   'exchange', 'with', '@angie1234p', 'at', 'the', '18thDec', ';', 'btw', 'SM', 'is', 'faster', 'has', 'also', 'an', 'agile', '...', '1', '/', '2', "'", '...', 'user', 'community', '-', 'http', ':', '/', '/', 'bit', '.', 'ly', '/', 'XnF5', '+', 'ICR', 'http', ':', '/', '/'] 

非常感谢任何帮助。非常感谢!

-弗洛里

请您参考如下方法:

在此分词器中,正则表达式用于指定要从文本中提取的分词的外观。 我有点困惑您使用了上面许多正则表达式中的哪一个,但是对于非空白标记的非常简单的标记化,您可以使用:

>>> corpus = "this is a sentence. and another sentence. my homepage is http://test.com" 
>>> nltk.regexp_tokenize(corpus, r"\S+") 
['this', 'is', 'a', 'sentence.', 'and', 'another', 'sentence.', 'my', 'homepage', 'is', 'http://test.com'] 

相当于:

>>> corpus.split() 
['this', 'is', 'a', 'sentence.', 'and', 'another', 'sentence.', 'my', 'homepage', 'is', 'http://test.com'] 

另一种方法是使用 nltk 函数 sent_tokenize() 和 nltk.word_tokenize():

>>> sentences = nltk.sent_tokenize(corpus) 
>>> sentences 
['this is a sentence.', 'and another sentence.', 'my homepage is http://test.com'] 
>>> for sentence in sentences: 
    print nltk.word_tokenize(sentence) 
['this', 'is', 'a', 'sentence', '.'] 
['and', 'another', 'sentence', '.'] 
['my', 'homepage', 'is', 'http', ':', '//test.com'] 

不过,如果您的文本包含大量网站 URL,这可能不是最佳选择。可以找到有关 NLTK 中不同分词器的信息 here .

如果您只想从语料库中提取 URL,您可以使用如下正则表达式:

nltk.regexp_tokenize(corpus, r'(http://|https://|www.)[^"\' ]+') 

希望这对您有所帮助。如果这不是您正在寻找的答案,请尝试更准确地解释您想要做什么以及您希望您的 token 看起来如何(例如,您想要的示例输入/输出)我们可以提供帮助找到正确的正则表达式。