Python: 文字匹配
Python: text matching
我有一个如下所示的数据库:
df['col'] = ['text', 'Texts', 'Text-Pro', 'Text;Nothing', 'Pro', 'pro', 'Pros', 'Nothing']
我想做的是迭代并找到这些值,但它不起作用:
for i in range(len(df['col']):
if df.loc[i, 'col'] in list(['text', 'pro']):
print('yes')
我想要的输出:
yes
yes
yes
yes
yes
yes
yes
这是您要找的吗?您基本上需要检查列中的 'text'
或 'pro'
。因此,您应该将这 2 个字符串 与 列进行比较。
import pandas as pd
df=pd.DataFrame()
df['col'] = ['text', 'Texts', 'Text-Pro', 'Text;Nothing', 'Pro', 'pro', 'Pros', 'Nothing']
list1=[]
for i in range(len(df['col'])):
if 'text' in str(df['col'][i]).lower() or 'pro' in str(df['col'][i]).lower():
list1.append("yes")
else:
list1.append("no")
df['Test/Pro']=list1
print(df)
输出:
col Test/Pro
0 text yes
1 Texts yes
2 Text-Pro yes
3 Text;Nothing yes
4 Pro yes
5 pro yes
6 Pros yes
7 Nothing no
您可以使用正则表达式和布尔掩码。您可能需要更新正则表达式以匹配您的用例。
import pandas as pd
df = pd.DataFrame()
df['col'] = ['text', 'Texts', 'Text-Pro', 'Text;Nothing', 'Pro', 'pro', 'Pros', 'Nothing']
masking = df['col'].str.contains(r'(Text|text)|(Pro|pro)')
print(masking)
打印
0 True
1 True
2 True
3 True
4 True
5 True
6 True
7 False
Name: col, dtype: bool
下面的答案应该是你问的。请注意,我重新构建了一些项目,以便更好地与您的 DataFrame 配合使用。 (根据您的代码,我假设您正在使用 pandas)。
import pandas
# outsource the matching to a function so we can use `map` below
def match_string(input_string):
"""
"""
target_strings = ['text', 'pro']
for target in target_strings:
# you need to lower your strings if you want the match to be case-insensitive
if target in input_string.lower():
print("yes")
return "yes"
print("no")
return "no"
df = pandas.DataFrame()
df['col'] = ['text', 'Texts', 'Text-Pro', 'Text;Nothing', 'Pro', 'pro', 'Pros', 'Nothing']
# instead of iterating, use a map operation which is much more efficient
# this will store the result in the column 'string_matched' as well as print it out as the question requests
df["string_matched"] = df["col"].map(lambda x: match_string(x))
您可以在 pandas 地图 here 周围找到一些文档。
输出
yes
yes
yes
yes
yes
yes
yes
no
在遍历数据帧时与 2 个必需的字符串进行比较。
import pandas as pd
df = pd.DataFrame()
df['col'] = ['text', 'Texts', 'Text-Pro', 'Text;Nothing', 'Pro', 'pro', 'Pros', 'Nothing']
for i in range(len(df['col'])):
if 'PRO' in str(df['col'][i]).upper() or 'TEXT' in str(df['col'][i]).upper():
print("yes")
else:
print("no")
输出
yes
yes
yes
yes
yes
yes
yes
no
我有一个如下所示的数据库:
df['col'] = ['text', 'Texts', 'Text-Pro', 'Text;Nothing', 'Pro', 'pro', 'Pros', 'Nothing']
我想做的是迭代并找到这些值,但它不起作用:
for i in range(len(df['col']):
if df.loc[i, 'col'] in list(['text', 'pro']):
print('yes')
我想要的输出:
yes
yes
yes
yes
yes
yes
yes
这是您要找的吗?您基本上需要检查列中的 'text'
或 'pro'
。因此,您应该将这 2 个字符串 与 列进行比较。
import pandas as pd
df=pd.DataFrame()
df['col'] = ['text', 'Texts', 'Text-Pro', 'Text;Nothing', 'Pro', 'pro', 'Pros', 'Nothing']
list1=[]
for i in range(len(df['col'])):
if 'text' in str(df['col'][i]).lower() or 'pro' in str(df['col'][i]).lower():
list1.append("yes")
else:
list1.append("no")
df['Test/Pro']=list1
print(df)
输出:
col Test/Pro
0 text yes
1 Texts yes
2 Text-Pro yes
3 Text;Nothing yes
4 Pro yes
5 pro yes
6 Pros yes
7 Nothing no
您可以使用正则表达式和布尔掩码。您可能需要更新正则表达式以匹配您的用例。
import pandas as pd
df = pd.DataFrame()
df['col'] = ['text', 'Texts', 'Text-Pro', 'Text;Nothing', 'Pro', 'pro', 'Pros', 'Nothing']
masking = df['col'].str.contains(r'(Text|text)|(Pro|pro)')
print(masking)
打印
0 True
1 True
2 True
3 True
4 True
5 True
6 True
7 False
Name: col, dtype: bool
下面的答案应该是你问的。请注意,我重新构建了一些项目,以便更好地与您的 DataFrame 配合使用。 (根据您的代码,我假设您正在使用 pandas)。
import pandas
# outsource the matching to a function so we can use `map` below
def match_string(input_string):
"""
"""
target_strings = ['text', 'pro']
for target in target_strings:
# you need to lower your strings if you want the match to be case-insensitive
if target in input_string.lower():
print("yes")
return "yes"
print("no")
return "no"
df = pandas.DataFrame()
df['col'] = ['text', 'Texts', 'Text-Pro', 'Text;Nothing', 'Pro', 'pro', 'Pros', 'Nothing']
# instead of iterating, use a map operation which is much more efficient
# this will store the result in the column 'string_matched' as well as print it out as the question requests
df["string_matched"] = df["col"].map(lambda x: match_string(x))
您可以在 pandas 地图 here 周围找到一些文档。
输出
yes
yes
yes
yes
yes
yes
yes
no
在遍历数据帧时与 2 个必需的字符串进行比较。
import pandas as pd
df = pd.DataFrame()
df['col'] = ['text', 'Texts', 'Text-Pro', 'Text;Nothing', 'Pro', 'pro', 'Pros', 'Nothing']
for i in range(len(df['col'])):
if 'PRO' in str(df['col'][i]).upper() or 'TEXT' in str(df['col'][i]).upper():
print("yes")
else:
print("no")
输出
yes
yes
yes
yes
yes
yes
yes
no