如何将TXT文件中的合并字符串拆分为列表并转换为Pandas DataFrame?
音频转文本文件转录
从文本文件转换为Pandas DataFrame。
当前读取文件的代码:
with open('random.txt', 'r') as f: for line in f: print(line) f.close()
当前输出:
['0.68', '2.54', 'Yes, I believe so.']['3.74', '4.04', ' Agree']['6.74', '8.3', 'I, also agree']
期望输出:
| Start | End | Text |
|---|---|---|
| 0.68 | 2.54 | Yes, I believe so. |
| 3.74 | 4.04 | Agree |
| 6.74 | 8.3 | I, also agree |
希望用正则表达式实现,也接受其他解决方案。
解决方案
方法一:正则表达式解析
通过正则匹配提取每组的起始时间、结束时间和文本,再整理成DataFrame:
import re import pandas as pd # 读取文件完整内容 with open('random.txt', 'r') as f: content = f.read() # 匹配格式为['数字', '数字', '文本']的分组 pattern = r"\['([\d.]+)', '([\d.]+)', '([^']+)'\]" matches = re.findall(pattern, content) # 清理文本中的多余空格并构造数据列表 cleaned_data = [[start, end, text.strip()] for start, end, text in matches] # 转换为DataFrame df = pd.DataFrame(cleaned_data, columns=['Start', 'End', 'Text']) print(df)
方法二:字符串直接处理
如果文件格式固定,可通过替换特殊字符后分割,实现更简洁:
import pandas as pd with open('random.txt', 'r') as f: content = f.read().replace('[', '').replace(']', '').replace("'", "") # 按逗号分割后每3个元素为一组 items = content.split(', ') data = [items[i:i+3] for i in range(0, len(items), 3)] # 转换为DataFrame,可选将时间列转为数值类型 df = pd.DataFrame(data, columns=['Start', 'End', 'Text']) df[['Start', 'End']] = df[['Start', 'End']].astype(float) print(df)
内容的提问来源于stack exchange,提问作者Yermo
相关产品推荐
相关产品推荐

