Python 列表列的列表比较

Python 列表列的列表比较,python,regex,pandas,list,Python,Regex,Pandas,List,我有一个表示库的数据框。这些列表示元数据,如作者、标题、年份和文本。文本列包含书籍文本的列表,其中每个列表元素表示书籍中的一个句子(见下文) 我想对这些句子进行NLP分析。对于单个示例,我将使用列表比较,但是如何以最符合python的方式对列使用列表比较呢 我想做的是,例如,创建一个新列,列中包含单词“the”,例如在本例中: 但是,它们使用带有字符串列而不是列表列的数据帧 您可以使用DataFrame.apply和正则表达式来实现这一点 重新导入 作为pd进口熊猫 数据={ “作者”:[史密斯

我有一个表示库的数据框。这些列表示元数据,如作者、标题、年份和文本。文本列包含书籍文本的列表,其中每个列表元素表示书籍中的一个句子(见下文)

我想对这些句子进行NLP分析。对于单个示例,我将使用列表比较,但是如何以最符合python的方式对列使用列表比较呢

我想做的是,例如,创建一个新列,列中包含单词
“the”
,例如在本例中:


但是,它们使用带有字符串列而不是列表列的数据帧

您可以使用
DataFrame.apply
和正则表达式来实现这一点

重新导入
作为pd进口熊猫
数据={
“作者”:[史密斯”,“格林],
“标题”:[“ABC”,“XYZ”],
“文本”:[
[“这是第一句话”,“这是第二句话”],
[“也是一句话”,“和第二句”]
]
}
df=pd.DataFrame(数据)
代币=[
“第一”,
"第二",,
“th”
]
def find_令牌(文本列表、重模式):
结果=[
文本
对于文本列表中的文本
如果重新搜索(重新搜索模式,text.lower())
]
如果结果为:
返回结果
返回
对于令牌中的令牌:
re|u pattern=re.compile(fr'(^ |\s){token}($|\s)'))
df[token]=df['Text'].apply(lambda x:find_token(x,re_模式))
与令牌重新匹配
word

所以必须有空格或句首/句尾。
re.compile(r'(^ |\s)
表示空白或开始。
re.compile(r'($|\s)
表示空白或结束

如果使用“th”作为标记,结果将是
None

将标记用作['first','second','th',],结果如下

  Author Title                                               Text  \
0  Smith   ABC  [This is the first sentence, This is the secon...   
1  Green   XYZ         [Also a sentence, And the second sentence]   

                          first                         second    th  
0  [This is the first sentence]  [This is the second sentence]  None  
1                          None      [And the second sentence]  None  

您可以使用
DataFrame.apply
和正则表达式来实现这一点

重新导入
作为pd进口熊猫
数据={
“作者”:[史密斯”,“格林],
“标题”:[“ABC”,“XYZ”],
“文本”:[
[“这是第一句话”,“这是第二句话”],
[“也是一句话”,“和第二句”]
]
}
df=pd.DataFrame(数据)
代币=[
“第一”,
"第二",,
“th”
]
def find_令牌(文本列表、重模式):
结果=[
文本
对于文本列表中的文本
如果重新搜索(重新搜索模式,text.lower())
]
如果结果为:
返回结果
返回
对于令牌中的令牌:
re|u pattern=re.compile(fr'(^ |\s){token}($|\s)'))
df[token]=df['Text'].apply(lambda x:find_token(x,re_模式))
与令牌重新匹配
word

所以必须有空格或句首/句尾。
re.compile(r'(^ |\s)
表示空白或开始。
re.compile(r'($|\s)
表示空白或结束

如果使用“th”作为标记,结果将是
None

将标记用作['first','second','th',],结果如下

  Author Title                                               Text  \
0  Smith   ABC  [This is the first sentence, This is the secon...   
1  Green   XYZ         [Also a sentence, And the second sentence]   

                          first                         second    th  
0  [This is the first sentence]  [This is the second sentence]  None  
1                          None      [And the second sentence]  None