我有一个 Python 脚本,它从 JSON 文件加载搜索词并处理 Pandas DataFrame 以添加新列,指示文本数据中是否存在某些词。但是,我想修改脚本以使用 Polars 而不是 Pandas,并可能删除 JSON 依赖项。这是我的原始代码:
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
# Example Usage
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 文件的示例:
{
"type1": {
"words": ["apple", "tasty"],
"exact_phrases": ["soccer ball"]
},
"type2": {
"words": ["banana"],
"exact_phrases": ["red apple"]
}
}
我知道我可以使用 .str.contains() 函数,但我想将它与特定的单词和确切的短语一起使用。您能否提供一些有关如何开始使用此功能的指导?
.str.contains_any()
可能是更好的选择。
您似乎想连接两个列表:
word_list = pl.read_json("word_list.json")
word_list = word_list.with_columns(
type1 = pl.concat_list(pl.col("type1").struct.field("*")),
type2 = pl.concat_list(pl.col("type2").struct.field("*"))
)
Shape: (1, 2)
┌───────────────────────────────────┬─────────────────────────┐
│ type1 ┆ type2 │
│ --- ┆ --- │
│ list[str] ┆ list[str] │
╞═══════════════════════════════════╪═════════════════════════╡
│ ["apple", "tasty", "soccer ball"] ┆ ["banana", "red apple"] │
└───────────────────────────────────┴─────────────────────────┘
您可以
.concat()
将它们放入您的框架中并运行 .contains_any()
new_df = pl.concat([df, word_list], how="horizontal")
new_df.with_columns(
type1 = pl.col("text_column").str.contains_any(pl.col("type1").flatten()),
type2 = pl.col("text_column").str.contains_any(pl.col("type2").flatten())
)
shape: (3, 3)
┌─────────────────────────────┬───────┬───────┐
│ text_column ┆ type1 ┆ type2 │
│ --- ┆ --- ┆ --- │
│ str ┆ bool ┆ bool │
╞═════════════════════════════╪═══════╪═══════╡
│ The apple is red ┆ true ┆ false │
│ I like bananas ┆ false ┆ true │
│ Cherries are tasty ┆ true ┆ false │
└─────────────────────────────┴───────┴───────┘