如何使用 python 和正则表达式计算有多少 \n (新行)?

How can I count how many \n (new lines) using python and regular expressions?

有没有办法计算一组文本中的行数?例如:

text="hello what are you"\
"doing with yourself"\
"this weekend?"

我要统计“\n”。我知道我可以用正则 python 来计算这个,但只是想知道是否有办法用正则表达式来计算这个?

是的,您可以使用正则表达式来计算换行数。

运行 re.findall() 并计算结果。

len(re.findall('\n', text))

例如,在我的 Linux 电脑上:

In [5]: with open('/etc/passwd') as fp: text = fp.read()

In [6]: len(re.findall('\n', text))
Out[6]: 56

但说真的,你为什么要这么做?正如您所指出的,已经有更好的方法可以做到这一点。

旁注

在你的情况下 text.

中没有换行符

可能您想定义

text = """hello what are you
doing with yourself
this weekend?"""

回答

您不需要正则表达式。

只需使用text.count("\n")~

编辑:哦,没关系。您需要它作为正则表达式吗?

len(re.findall("\n", text)) 应该有效

您还可以使用枚举来计算文件中的行数,如下所示:

with open (file, "r") as fp:
    for cnt, _ in enumerate (fp,1):
        pass
    print(cnt)