【问题标题】:issue with python and whatsapppython和whatsapp的问题
【发布时间】:2021-12-08 11:58:15
【问题描述】:

我将whatsapp中的数据提取到一个txt文件中 我需要在输出文件中创建 4 列日期、时间、名称和消息

import pandas as pd

# read file by lines
with open('D:\Analysis\example_chat_whatsapp.txt', encoding="utf-8") as f: 
     data=f.readlines()


# # sanity stats
print('num lines: %s' %(len(data)))

# parse text and create list of lists structure
# remove first whatsapp info message
dataset = data[1:]
cleaned_data = []
for line in dataset:
# grab the info and cut it out
    date = line.split(" ")[0]
    line2 = line[len(date):]
    time = line2.split(" ")[0][:2]
    line3 = line2[len(time):]
    name = line3.split(":")[0][:4]
    line4 = line3[len(name):]
    message = line4[6:-1] # strip newline charactor

    #print(date, time, name, message)
cleaned_data.append([date, time, name, message])

  
#Create the DataFrame 
df = pd.DataFrame(cleaned_data, columns = ['Date', 'Time', 'Name', 'Message']) 
df

我遇到的问题是变量时间(空)和名称输出错误。 日期和消息没有问题,有预期的输出

【问题讨论】:

  • 能否请您提供所有代码而不是图片链接?
  • 只提供您文件中的一行,我们不是媒介。

标签: python file whatsapp txt


【解决方案1】:

如果未注释 print(date, time, name, message) 打印有效数据,则只需在 cleaned_data.append([date, time, name, message]) 前添加 4 个空格。

for line in dataset:
    # grab the info and cut it out
    date = line.split(" ")[0]
    line2 = line[len(date) + 1:]
    time = line2.split(" ")[0]
    line3 = line2[len(time):]
    name = line3.split(":")[0]
    line4 = line3[len(name):]
    message = line4
    
    row = (date[1:], time[:-1], name[1:], message[2:-1])
    # print("'%s', '%s', '%s', '%s'" % row)
    cleaned_data.append(row)

s[1:] 返回 s 并删除第一个字符,s[:-1] 返回 s 并删除最后一个字符,依此类推。

【讨论】:

  • 我不知道为什么我不能在帖子中包含输出的图片
  • 不需要图片,只要example_chat_whatsapp.txt中的任何一行。
  • ‎[18/12/20 22:20:54] 用户 UV:‎imagen omitida
  • 以上是一行的例子
  • 效果很好,只有一个问题.....??更新了我的代码
猜你喜欢
  • 2017-02-23
  • 1970-01-01
  • 2023-01-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-09-01
  • 1970-01-01
相关资源
最近更新 更多