簡體   English   中英

如何使用python nltk刪除不顯示任何模式的亂碼?

[英]how to remove gibberish that exhibits no pattern using python nltk?

我正在編寫代碼來清理 url 並僅提取底層文本。

 train_str = train_df.to_string()
 letters_only = re.sub("[^a-zA-Z]", " ", train_str)
 words = letters_only.lower().split()
 stops = set(stopwords.words("english"))
 stops.update(['url','https','http','com'])
 meaningful_words = [w for w in words if not w in stops]
 long_words = [w for w in meaningful_words if len(w) > 3]

使用上面的代碼,我可以在刪除標點符號、停用詞等之后只提取單詞。但我無法刪除本質上是胡言亂語的單詞。 這些是我清理 url 后得到的許多詞中的一些。

['uact', 'ahukewim', 'asvpoahuhxbqkhdtibveqfggtmam', 'fchrisalbon','afqjcnhil', 'ukai', 'khnaantjejdfrhpeza']

它們的出現或字母中沒有特定的模式來使用正則表達式或其他函數。 任何人都可以提出任何可以刪除這些詞的方法嗎? 謝謝!

創建一個空列表。 循環遍歷當前列表中的所有單詞。 使用words.words()來檢查它是否是真實世界。 將所有“非垃圾詞”附加到該新列表中。 根據您的需要使用該新列表。

from nltk.corpus import words

test = ['uact', 'ahukewim', 'asvpoahuhxbqkhdtibveqfggtmam', 'fchrisalbon',\
'afqjcnhil', 'ukai', 'khnaantjejdfrhpeza', 'this', 'is' , 'a' , 'word']
final = []

for x in test:
    if x in words.words():
        final.append(x)
print(final)

輸出:

['this', 'is', 'a', 'word']

你可以這樣做:

import nltk
nltk.download('words')

words = set(nltk.corpus.words.words())

sent = "basldlad and Rakadajlnv  share"

" ".join(w for w in nltk.wordpunct_tokenize(sent) \

         if w.lower() in words or not w.isalpha())

1.) 'nltk.download('words')' 下載英語單詞的語料庫。

2.) 'set(nltk.corpus.words.words())' 創建一組英語單詞並將其分配給單詞。

3.) 最后一個循環只是從你的句子中提取每個單詞,並檢查它是否是單詞語料庫的一部分,也不是字母數字。

4.) 請注意,像人名這樣的專有名詞在這里也會被視為胡言亂語。

5.) 為了處理專有名詞,您需要進行命名實體識別

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM