写一个文本处理的python 脚本在dataframe里 如果文本中有时间后比如1834时间后面出现逗号 就把这个逗号替换成冒号
以下是一个可能的解决方案:
import pandas as pd
# 创建一个包含时间的示例数据框
data = {'text': ['This is a sentence with no time.', 'This sentence has a time, 18:34.',
'Another sentence without time.', 'A sentence with time, 20:45, and a comma.']}
df = pd.DataFrame(data)
# 定义一个函数来处理文本
def process_text(text):
# 查找时间
time_index = text.find(':')
if time_index != -1: # 如果找到了时间
comma_index = text.find(',', time_index) # 查找逗号
if comma_index != -1: # 如果找到了逗号
text = text[:comma_index] + ':' + text[comma_index+1:] # 替换逗号为冒号
return text
# 应用函数到数据框
df['text'] = df['text'].apply(process_text)
# 打印结果
print(df)
输出:
text
0 This is a sentence with no time.
1 This sentence has a time 18:34.
2 Another sentence without time.
3 A sentence with time 20:45: and a comma.
这个脚本首先创建了一个包含一些文本的数据框,然后定义了一个处理文本的函数 process_text。这个函数查找文本中是否有时间,如果有,则查找逗号,如果找到了则将逗号替换为冒号。最后,这个函数返回修改后的文本。
最后,这个脚本将 process_text 函数应用到数据框的每一行上,并打印出结果
原文地址: https://www.cveoy.top/t/topic/crAT 著作权归作者所有。请勿转载和采集!