Python 中的文本解析

发布于 2024-11-25 22:00:05 字数 213 浏览 1 评论 0原文

我知道这是一件容易的事,但我对编程是全新的,任何帮助将不胜感激。

我有一个文本文件,其中包含一堆数字(每行一个)。我需要打开文件并将数字分成三个。如果数字是“123456”,我需要将其拆分为“14”,“25”,“36”,换句话说,我需要它去(x1x2),(y1y2),(z1,z2)得到数字x1y1z1x2y2z2。对于奇数,我想在最后一组中添加一个零以使其均匀。感谢您的帮助,我对编程毫无希望。

I know this is an easy one but I am brand new to programming and any help would be greatly appreciated.

I have a text file that has a bunch of numbers in it (one per line). I need to open the file and split the number into three. If the number is "123456" i need to split it into "14","25","36" in other words I need it to go (x1x2), (y1y2), (z1,z2) for a number x1y1z1x2y2z2. For odd numbers I want to add a zero to the last group to even it out. Thanks for the help, I am hopeless at programming.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

追风人 2024-12-02 22:00:05

一个简单的建议。将您的号码隐藏到列表中并对列表的元素进行操作。

>>> list("123456")
['1', '2', '3', '4', '5', '6']
>>> 

现在,你处理起来会容易得多。如果没有,那么您也许应该从一些 Python 教程开始。

One simple suggestion. Covert your number to a list and operate on the elements of the list.

>>> list("123456")
['1', '2', '3', '4', '5', '6']
>>> 

Now, it would much easier for you to handle. If not, then you should perhaps start with some Python tutorials.

素罗衫 2024-12-02 22:00:05

这应该满足您的示例:

s = "123456"
ss = [s[i::3] for i in range(3)]
ss
> ['14', '25', '36']

要确保字符串长度相等,您可以填充原始字符串:

s = s.ljust((len(s)+2)//3 * 3, '0')

或执行以下操作:

l = (len(s)+2)//3
ss = [s[i::3].ljust(l, '0') for i in range(3)]

This should satisfy your example:

s = "123456"
ss = [s[i::3] for i in range(3)]
ss
> ['14', '25', '36']

To make sure the strings are equal length, you can either pad the original string:

s = s.ljust((len(s)+2)//3 * 3, '0')

or do:

l = (len(s)+2)//3
ss = [s[i::3].ljust(l, '0') for i in range(3)]
懷念過去 2024-12-02 22:00:05

因此,因为您要切成三份,所以问题不是奇数,而是不能被 3 整除的数字。这是一个接受字符串并返回该字符串切片元组的函数。

def triplet(s):
    extra_zeros = (3 - len(s)) % 3
    s += '0' * extra_zeros
    return (s[::3], s[1::3], s[2::3])

这是其行为的演示:

>>> triplet('123456')
('14', '25', '36')
>>> triplet('1234567')
('147', '250', '360')
>>> triplet('12345678')
('147', '258', '360')
>>> triplet('123456789')
('147', '258', '369')

So because you're slicing into thirds, the problem isn't odd numbers, but is rather numbers not divisible by 3. Here's a function that accepts a string and returns a tuple of slices of that string.

def triplet(s):
    extra_zeros = (3 - len(s)) % 3
    s += '0' * extra_zeros
    return (s[::3], s[1::3], s[2::3])

Here's a demonstration of its behavior:

>>> triplet('123456')
('14', '25', '36')
>>> triplet('1234567')
('147', '250', '360')
>>> triplet('12345678')
('147', '258', '360')
>>> triplet('123456789')
('147', '258', '369')
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文