[英]KeyError despite Key exists
這是一個適用於我的數據框的函數 我的計算機上有一個名為“100-contacts”的 csv 文件,該文件包含有關郵件的信息,例如名字、地址、城市等。我的目標是檢測垃圾郵件郵件。 我需要清除停用詞和標點符號中的數據,這部分代碼會對我有所幫助,但盡管存在 Key,但我還是收到了KeyError
。
def process_text(text):
#1 Remove puntcuation
#2 Remove stopwords
#3 Return a list of clean text words
#1
nopunc = [char for char in text if char not in string.punctuation]
nopunc = ' '.join(nopunc)
#2
clean_words = [word for word in nopunc.split() if word.lower() not in stopwords.words('english')]
#3
return clean_words
df['text'].head().apply(process_text)
您的列名中可能有空格。 在將 CSV 讀入 DataFrame 時添加sep=r'\\s*,\\s*'
可能會有所幫助。
import pandas as pd
import string
from nltk.corpus import stopwords
# csv.csv
# name, age, text
# aa, 11, randomtext
# bb, 22, randomtexttext
# cc, 33, ra..ndo..mtexttext
df = pd.read_csv('csv.csv', header=0, sep=r'\s*,\s*')
def process_text(text):
#1 Remove puntcuation
#2 Remove stopwords
#3 Return a list of clean text words
#1
nopunc = [char for char in text if char not in string.punctuation]
nopunc = ' '.join(nopunc)
#2
clean_words = [word for word in nopunc.split() if word.lower() not in stopwords.words('english')]
#3
return clean_words
print(df['text'].head().apply(process_text))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.