python - 如何使用特定格式的熊猫从文本文件中读取数据?
问题描述
我有一个包含如下数据的文本文件。
20/12/2018
This is the test text.
22/12/2018
* 21/12/2018
This is a test text where the text is written on later than the actual date.
现在让我们说,上面的数据与文本文件 (text.txt) 中的日期。我需要一种方法来读取该数据并将其放在熊猫数据框中。我想将它们读入列中,
日期文本 DateOfWritten
日期将采取应该是文本的实际日期。例如,21/22/2018 应该是日期。22/12/2018 应该是 DateOfWritten
提前致谢。
解决方案
这可能是一种解决方案
from collections import defaultdict
import pandas as pd
dict_for_df = defaultdict(list)
last_find = None
last_date = None
with open("test.txt",'r') as f:
for line in f.readlines():
curr_find = line.find("/")
if line == "\n":
continue
elif curr_find == 2:
Date = line.replace("\\n","").strip()
dict_for_df['DateOfWritten'].append(Date)
last_date = Date
last_find = 2
elif (last_find == 2 and curr_find != 4):
dict_for_df['Date'].append(last_date)
dict_for_df['text'].append(line.replace("\n","").strip())
last_find = 0
last_date = ''
elif curr_find == 4:
dict_for_df['Date'].append(line.replace("*","").replace("\n","").strip())
last_date = ""
last_find = None
else:
dict_for_df['text'].append(line.replace("\n","").strip())
last_date = ""
last_find = None
df = pd.DataFrame(dict_for_df)
推荐阅读
- php - 带有作曲家的交互式 PHP 脚本
- ios - 在 Int Swift 中插入一个字符
- c# - 写2个几乎相同的函数更好,还是根据输入变量确定逻辑
- kaa - 是否可以在 KAA IoT 解决方案中将文件传输到端点?
- python-3.x - 使用 urllib.error 中的 try catch 检查连接状态时发生另一个异常
- python - Qlik sense ssl.SSLError: [SSL: CERTIFICATE_VERIFY_FAILED] 证书验证失败 (_ssl.c:749)
- laravel - 我应该如何在 Laravel 包中输入提示 UserModel?
- sql - 递归关系的实现
- vba - 使用 VBA 在 IE11 中关闭框架通知栏
- php - PHP Parse 错误:语法错误,第 56 行出现意外的“[”