我最近正在研究python回圈,我想試試是否可以使用for回圈來洗掉停用詞和標點符號。
但是,我的代碼不起作用,它顯示標點符號未定義。(由于評論可以洗掉停用詞)
我知道它可以使用串列理解來實作,并且 StackOverflow 中有很多答案,但我想知道如何使用 for 回圈來實作。
我用于練習的代碼如下:
texts = 'I love python, From John'
stopword = ['i', 'from']
punctuations = ','
texts = texts.split()
empty_list = []
for text in texts:
text = text.lower()
if text not in stopword and punctuation not in punctuations:
empty_list.append(text)
print(empty_list)
預期的輸出將是love python John
謝謝您的幫助
uj5u.com熱心網友回復:
標點符號可以附加到單詞上,以便用戶替換。
然后將文本拆分為單詞,將它們轉換為較低的單詞,并為每個單詞檢查它是否存在于停用詞中
text = 'I love python, From John'
stopwords = ['i', 'from']
punctuations = [',']
# first remove punctuations
for p in punctuations:
text = text.replace(p, "")
# then split the text string and for each element check if it exist in stopwords
result = []
for word in text.split():
if word.lower() not in stopwords:
result.append(word)
# join into string
result = " ".join(result)
結果:
'love python John'
uj5u.com熱心網友回復:
您可以將其作為串列理解來執行,并避免像這樣的 for 回圈:
texts = 'I love python, from John'
stopword = ['I', 'from']
punctuations = [',']
[word for word in texts.split(' ') if word not in stopword and word not in [',']]
//['love', 'python,', 'John']
uj5u.com熱心網友回復:
您正在使用該回圈遍歷字符。您應該使用 .split() 方法將字串拆分為單詞(例如使用 ' ' 進行拆分),然后您將能夠從使用 .split() 創建的單詞串列中 .pop() 那些單詞。
uj5u.com熱心網友回復:
你可以試試這個:
import string
texts = 'I love python, From John'
stopword = ['i, from']
text = texts.translate(str.maketrans('','',string.punctuation)).lower().split(' ')
empty_list = [word for word in text if word not in stopword]
我添加了標點符號洗掉器以擺脫',來自','來自?否則不會看到
uj5u.com熱心網友回復:
因此,如果我正確理解了您的問題,答案將是在您找到停用詞中的單詞后使用 pop 指令。
第一個錯誤是在停用詞串列中,因為那里只有一個元素,需要像下面的示例一樣分隔元素:
list = ['one', 'two', 'three']
在此提及之后,您還需要一個指令,如洗掉洗掉不需要的元素。
所以實作將如下:
texts = 'I love python, From John'
stopword = ['i', 'from']
texts = texts.split()
empty_list = []
for text in texts:
text_original = text
text = text.lower()
if text not in stopword:
empty_list.append(text_original)
#print(empty_string)
else:
texts.remove(text_original)
print(texts, empty_list)
希望對您有所幫助。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/511145.html
標籤:Python循环停用词
