我有一段Python脚本,它从一个JSON文件中加载搜索词,并处理Pandas DataFrame以添加新列,指示文本数据中是否存在某些词。然而,我想修改脚本,使用Polars而不是Pandas,并可能去除对JSON的依赖。这是我原始的代码:
```python
import pandas as pd
import json
class SearchTermLoader:
def __init__(self, json_file):
self.json_file = json_file
def load_terms(self):
with open(self.json_file, 'r') as f:
data = json.load(f)
terms = {}
for phase_name, phase_data in data.items():
terms[phase_name] = (
phase_data.get('words', []),
phase_data.get('exact_phrases', [])
)
return terms
class DataFrameProcessor:
def __init__(self, df: pd.DataFrame, col_name: str) -> None:
self.df = df
self.col_name = col_name
def add_contains_columns(self, search_terms):
columns_to_add = ["type1", "type2"]
for column in columns_to_add:
self.df[column] = self.df[self.col_name].apply(
lambda text: any(
term in text
for term in search_terms.get(column, ([], []))[0] + search_terms.get(column, ([], []))[1]
)
)
return self.df
# 示例用法
data = {'text_column': ['The apple is red', 'I like bananas', 'Cherries are tasty']}
df = pd.DataFrame(data)
term_loader = SearchTermLoader('word_list.json')
search_terms = term_loader.load_terms()
processor = DataFrameProcessor(df, 'text_column')
new_df = processor.add_contains_columns(search_terms)
new_df
```
这是JSON文件的示例:
```json
{
"type1": {
"words": ["apple", "tasty"],
"exact_phrases": ["soccer ball"]
},
"type2": {
"words": ["banana"],
"exact_phrases": ["red apple"]
}
}
```
我知道我可以使用`.str.contains()`函数,但我想用它来匹配特定的词和确切的短语。你能提供一些如何开始的指导吗?
对于非正则表达式匹配,
.str.contains_any()
可能是一个更好的选择。看起来你想要连接这两个列表:
然后你可以将它们
.concat()
到你的框架中,并运行.contains_any()