在文本文件中找到一个模式(float +' \ t' + float)

时间:2017-09-13 09:48:22

标签: python regex pandas dataframe

我有一些文本文件,我想在哪一行找到一个带有float +' \ t' + float的模式。

文本文件如下所示:

some information: bla bla
test time: 1.34
something else 23.00
data1 data2
0.01 0.22
0.2 0.34
.....

data1之前的文本信息的行数可能不同,data1和data2也可能不同。

我更喜欢大熊猫的解决方案,但其他一切都是可以接受的。

4 个答案:

答案 0 :(得分:1)

^.*\d*\.\d+\t\d*\.\d+.*$

这将帮助您识别包含floatTABfloat值的行

Regex Demo

示例来源(run it here):

import re
regex = r"^.*\d*\.\d+\t\d*\.\d+.*$"
matches = re.finditer(regex, test_str, re.MULTILINE)
for match in matches:
    print(match.group(0))

答案 1 :(得分:1)

df

                        Col1
0  some information: bla bla
1            test time: 1.34
2       something else 23.00
3                data1 data2
4                  0.01 0.22
5                   0.2 0.34

df = df.Col1.str.extract('(\d+\.\d+\s\d+\.\d+)', expand=False).to_frame()
df
        Col1
0        NaN
1        NaN
2        NaN
3        NaN
4  0.01 0.22
5   0.2 0.34

要删除nan行,请使用df.dropna

        Col1
4  0.01 0.22
5   0.2 0.34

正则表达式细分

(       # open capture group
\d+     # any number of digits
\.      # literal dot (escaped)
\d+     
\s      # any whitespace (sub with \t for a more strict search)
\d+\.\d+ 
)       # close capture group

答案 2 :(得分:0)

首先需要一种方法来找到花车。 假设它们总是以点作为分隔符编写,以下将执行:

\d+(\.\d+)?

\d+            Match one or more digits
    \.\d+      Match a dot followed by one or more digits...
   (     )?    ... maybe

然后你需要匹配两个浮点数之间的空白字符:

\s+

全部放在一起:

\d+(\.\d+)?\s+\d+(\.\d+)?

使用Python和re进行测试:

import re

regex = re.compile("\d+(\.\d+)?\s+\d+(\.\d+)?")

print(regex.match("0.2 0.34"))
print(regex.match("0.01 0.22"))

输出:

<_sre.SRE_Match object; span=(0, 8), match='0.2 0.34'>
<_sre.SRE_Match object; span=(0, 9), match='0.01 0.22'>

现在,如果你想捕捉花车:

(\d+(\.\d+)?)\s+(\d+(\.\d+)?)

您会在论坛13中找到两个花车:

import re

regex = re.compile("(\d+(\.\d+)?)\s+(\d+(\.\d+)?)")

result = regex.match("0.2 0.34")
print(result.group(1))
print(result.group(3))

输出:

0.2
0.34

答案 3 :(得分:0)

您似乎在询问如何查找包含标签的行,而不只是查找包含空格的行。在这种情况下,你不需要这样的东西吗?

>>> import re
>>> re.match(r'^(?:[0-9.]+)\\t(?:[0-9.]+)$', r'0.01\t0.22')
<_sre.SRE_Match object; span=(0, 10), match='0.01\\t0.22'>

请注意在t之前存在双反斜杠。