Python 中的文本解析
我知道这是一件容易的事,但我对编程是全新的,任何帮助将不胜感激。
我有一个文本文件,其中包含一堆数字(每行一个)。我需要打开文件并将数字分成三个。如果数字是“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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
一个简单的建议。将您的号码隐藏到列表中并对列表的元素进行操作。
现在,你处理起来会容易得多。如果没有,那么您也许应该从一些 Python 教程开始。
One simple suggestion. Covert your number to a list and operate on the elements of the list.
Now, it would much easier for you to handle. If not, then you should perhaps start with some Python tutorials.
这应该满足您的示例:
要确保字符串长度相等,您可以填充原始字符串:
或执行以下操作:
This should satisfy your example:
To make sure the strings are equal length, you can either pad the original string:
or do:
因此,因为您要切成三份,所以问题不是奇数,而是不能被 3 整除的数字。这是一个接受字符串并返回该字符串切片元组的函数。
这是其行为的演示:
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.
Here's a demonstration of its behavior: