gpt4 book ai didi

python - 在 Python 中读取格式化的多行

转载 作者:太空宇宙 更新时间:2023-11-04 01:10:43 25 4
gpt4 key购买 nike

我想用 python 读取一些格式化的数据。数据的格式类似于这样:

00:00:00
1 1 1
1 1 1
1 1 1

00:00:02
3 3 3
3 3 3
3 3 3

我可以使用正向代码成功模拟 C/C++ 中的读取:

int main()
{
string hour;
int x0,y0,z0, x1,y1,z1, x2,y2,z2;

while(cin >> hour)
{
scanf("%d %d %d\n%d %d %d\n%d %d %d\n", &x0, &y0, &z0, &x1, &y1, &z1, &x2, &y2, &z2);
cout << hour << endl; //check the reading
}
return 0;
}

问题是我找不到像 scanf 那样简单的读取格式化多行字符串的 Python 方法。 np.genfromtxt 中的一些示例接近所需的内容,一些来自 struct.unpack 的示例,但我的技能不足以使其与多行一起工作。我可能可以使用 split() 和一些 readline 来准确获取格式化数据,但它让我发疯,因为 C/C++ 中的程序比 Python 中的程序更简单。有什么方法可以在 Python 中执行类似于 C/C++ 代码的操作吗?


在 Joril 的帮助下得到的答案是:

from scanf import sscanf
import sys

data = ''
for line in sys.stdin:
if line != '\n':
data += line
else:
print sscanf(data, "%s\n%d %d %d\n%d %d %d\n%d %d %d\n")
data = ''

作为输出我得到了类似的东西:

('00:00:00', 1, 1, 1, 1, 1, 1, 1, 1, 1)
('00:00:02', 3, 3, 3, 3, 3, 3, 3, 3, 3)

最佳答案

您绝对可以使用正则表达式。以下是没有循环的 python 中或多或少的匹配代码: 导入重新

hour = input()
res = re.match(
r'(?P<hour>\d\d):(?P<minute>\d\d):(?P<second>\d\d)\n' # \n'
r'(?P<x0>\d+) (?P<y0>\d+) (?P<z0>\d+)\n'
r'(?P<x1>\d+) (?P<y1>\d+) (?P<z1>\d+)\n'
r'(?P<x2>\d+) (?P<y2>\d+) (?P<z2>\d+)',
hour, re.MULTILINE)

if res:
print(res.groupdict())

我会先将数据拆分成行,然后再进行解析。

关于python - 在 Python 中读取格式化的多行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27882108/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com