简体   繁体   English

字符串中的条件替换 - Python

[英]Conditional replacing in a string - Python

I am very new to Python and programming.我对 Python 和编程很陌生。 I have a file with measurment values that looks like this:我有一个包含测量值的文件,如下所示:

85.2147....85.2150..85.2152..85.2166...85.2180.85.2190. 85.2147....85.2150..85.2152..85.2166...85.2180.85.2190。

At the end what I want to have is:最后我想要的是:
85.2147 85.2147
85.2150 85.2150
85.2152 85.2152
85.2166 85.2166
85.2180 85.2180
85.2190 85.2190

What I managed using我管理使用的

k = (j.replace('....', '\r'))
l = (k.replace('...', '\r'))
m = (l.replace('..', '\r'))

is this:这是:

85.2147 85.2147
85.2150 85.2150
85.2152 85.2152
85.2166 85.2166
85.2180.85.2190. 85.2180.85.2190。

Now, the question is, how can I conditionally replace single dots, A) if no numbers come after it;现在,问题是,如果后面没有数字,我如何有条件地替换单个点,A); and B) if the number after the point is the same as the 6th number (or 7th character) before the point. B) 如果点后的数字与点前的第 6 个数字(或第 7 个字符)相同。

You should read up on Python regular expressions and book mark a regular expression test page to help you solve these problems.您应该阅读Python 正则表达式并将正则表达式测试页标记为书签,以帮助您解决这些问题。 Also, it's good to remember that Python can be run in interactive mode to allow you to test things out by hand very quickly.此外,最好记住 Python 可以在交互模式下运行,以便您可以非常快速地手动测试。

>>> import re
>>> test = "85.2147....85.2150..85.2152..85.2166...85.2180.85.2190."
>>> target = re.compile(r'(\d+\.\d+)(\.+)')
>>> match = re.findall(target, test)
>>> match
[('85.2147', '....'), ('85.2150', '..'), ('85.2152', '..'), ('85.2166', '...'), ('85.2180', '.'), ('85.2190', '.')]
>>> res
['85.2147', '85.2150', '85.2152', '85.2166', '85.2180', '85.2190']
>>>
>>> import re
>>> string = '85.2147....85.2150..85.2152..85.2166...85.2180.85.2190.'
>>> result = re.findall('(\d+\.\d+)\.+',string)
>>> result
['85.2147', '85.2150', '85.2152', '85.2166', '85.2180', '85.2190']

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM