Python:将一个字符串解析为多个变量? [英] Python: Parse one string into multiple variables?

查看:241
本文介绍了Python:将一个字符串解析为多个变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很确定为此有一个功能,但是我已经搜索了一段时间,因此决定直接问SO.

I am pretty sure that there is a function for this, but I been searching for a while, so decided to simply ask SO instead.

我正在编写一个Python脚本,用于分析和分析来自输入文件的文本消息.每行看起来像这样:

I am writing a Python script that parses and analyzes text messages from an input file. Each line looks like this:

2014年10月24日,19:20-李·怀特:你好,世界!

Oct 24, 2014, 19:20 - Lee White: Hello world!

或:

4月4日,19:20-李·怀特:世界你好!

Apr 4, 19:20 - Lee White: Hello world!

如果未提及日期时间中的年份,则表示邮件是在当前年份中发送的.

If the year in the datetime is not mentioned, it means that the message was sent in the current year.

我想要做的是将此字符串解析为多个变量.理想情况下,我正在寻找一个函数,该函数需要一个输入字符串,一个格式字符串和几个变量来将输出存储在以下位置:

What I want to do, is parse this string into multiple variables. Ideally, I am looking for a function that takes an input string, a format string, and a couple of variables to store the output in:

foo(input, "MMM DD, YYYY, HH:MM - Sender: Text", &mon, &day, &year, &hour, &minutes, &sender, &text)

Python中是否存在这种东西?

Does such a thing exist in Python?

推荐答案

它使用非常有用的dateutil库使日期解析更加容易-您可以pip install python-dateutileasy_install python-dateutil.在:-上拆分数据以获取消息和发件人,然后处理日期文本以获取datetime对象,您可以在其中访问其各种属性以获取所需的组件,例如:

This uses the remarkably useful dateutil library to make date parsing easier - you can pip install python-dateutil or easy_install python-dateutil it. Split the data on the : and the - to get message and sender, then process the date text to get a datetime object where you can access its various attributes to get the components required, eg:

from dateutil.parser import parse

s = 'Apr 4, 19:20 - Lee White: Hello world!'
fst, _, msg = s.rpartition(': ')
date, _, name = fst.partition(' - ')
date = parse(date)
name, msg, date.year, date.month, date.day, date.hour, date.minute
# ('Lee White', 'Hello world!', 2015, 4, 4, 19, 20)

这篇关于Python:将一个字符串解析为多个变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆