简体   繁体   English

Python:从csv逐行提取关键字

[英]Python: extract keywords row by row from csv

I am trying to extract keywords line by line from a csv file and create a keyword field. 我试图从csv文件中逐行提取关键字并创建关键字字段。 Right now I am able to get the full extraction. 现在我能够完全提取。 How do I get keywords for each row/field? 如何获取每行/每个字段的关键字?

Data: 数据:

id,some_text
1,"What is the meaning of the word Himalaya?"
2,"Palindrome is a word, phrase, or sequence that reads the same backward as forward"

Code: This is search entire text but not row by row. 代码:这是搜索整个文本,但不是逐行搜索。 Do I need to put something else besides replace(r'\\|', ' ') ? 除了replace(r'\\|', ' ')之外我还需要放其他东西吗?

import pandas as pd
import nltk
from nltk.tokenize import word_tokenize
from nltk.corpus import stopwords

df = pd.read_csv('test-data.csv')
# print(df.head(5))

text_context = df['some_text'].str.lower().str.replace(r'\|', ' ').str.cat(sep=' ') # not put lower case?
print(text_context)
print('')
tokens=nltk.tokenize.word_tokenize(text_context)
word_dist = nltk.FreqDist(tokens)
stop_words = stopwords.words('english')
punctuations = ['(',')',';',':','[',']',',','!','?']
keywords = [word for word in tokens if not word in stop_words and not word in punctuations]
print(keywords)

final output: 最终输出:

id,some_text,new_keyword_field
1,What is the meaning of the word Himalaya?,"meaning,word,himalaya"
2,"Palindrome is a word, phrase, or sequence that reads the same backward as forward","palindrome,word,phrase,sequence,reads,backward,forward"

Here is a clean way to add a new keywords column to your dataframe using pandas apply. 以下是使用pandas apply向数据框添加新关键字列的简洁方法。 Apply works by first defining a function ( get_keywords in our case) that we can apply to each row or column. 应用首先定义一个函数(在我们的例子中为get_keywords ),我们可以它们应用于每一行或每列。

import pandas as pd
import nltk
from nltk.tokenize import word_tokenize
from nltk.corpus import stopwords

# I define the stop_words here so I don't do it every time in the function below
stop_words = stopwords.words('english')
# I've added the index_col='id' here to set your 'id' column as the index. This assumes that the 'id' is unique.
df = pd.read_csv('test-data.csv', index_col='id')  

Here we define our function that will be applied to each row using df.apply in the next cell. 这里我们定义我们的函数,它将在下一个单元格中使用df.apply应用于每一行。 You can see that this function get_keywords takes a row as its argument and returns a string of comma separated keywords like you have in your desired output above ("meaning,word,himalaya"). 你可以看到,这个功能get_keywords需要一个row作为它的参数和返回逗号分隔的关键字串像你所需输出具有上述(“之意,字,喜马拉雅”)。 Within this function we lower, tokenize, filter out punctuation with isalpha() , filter out our stop_words, and join our keywords together to form the desired output. 在这个函数中,我们降低,标记化,使用isalpha()过滤掉标点符号,过滤掉我们的stop_words,并将我们的关键字连接在一起以形成所需的输出。

# This function will be applied to each row in our Pandas Dataframe
# See the docs for df.apply at: 
# https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.apply.html
def get_keywords(row):
    some_text = row['some_text']
    lowered = some_text.lower()
    tokens = nltk.tokenize.word_tokenize(lowered)
    keywords = [keyword for keyword in tokens if keyword.isalpha() and not keyword in stop_words]
    keywords_string = ','.join(keywords)
    return keywords_string

Now that we have defined our function that will be applied we call df.apply(get_keywords, axis=1) . 现在我们已经定义了将要应用的函数,我们调用df.apply(get_keywords, axis=1) This will return a Pandas Series (similar to a list). 这将返回一个Pandas系列(类似于列表)。 Since we want this series to be a part of our dataframe we add it as a new column using df['keywords'] = df.apply(get_keywords, axis=1) 由于我们希望此系列成为数据df['keywords'] = df.apply(get_keywords, axis=1)的一部分,因此我们使用df['keywords'] = df.apply(get_keywords, axis=1)将其添加为新列

# applying the get_keywords function to our dataframe and saving the results
# as a new column in our dataframe called 'keywords'
# axis=1 means that we will apply get_keywords to each row and not each column
df['keywords'] = df.apply(get_keywords, axis=1)

Output: Dataframe after adding 'keywords' column 输出: 添加“关键字”列后的数据框

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM