【问题标题】:Regex FindAll occurances of a string inside a text file. How?正则表达式 FindAll 出现在文本文件中的字符串。如何?
【发布时间】:2026-02-26 22:45:01
【问题描述】:

第一步:我生成 25 位小数的 Pi 并将其保存到 output.txt 文件中。

from decimal import *

#Sets decimal to 25 digits of precision
getcontext().prec = 25

def factorial(n):
    if n<1:
        return 1
    else:
        return n * factorial(n-1)

def chudnovskyBig(): #http://en.wikipedia.org/wiki/Chudnovsky_algorithm
    n = 1
    pi = Decimal(0)
    k = 0
    while k < n:
        pi += (Decimal(-1)**k)*(Decimal(factorial(6*k))/((factorial(k)**3)*(factorial(3*k)))* (13591409+545140134*k)/(640320**(3*k)))
        k += 1
    pi = pi * Decimal(10005).sqrt()/4270934400
    pi = pi**(-1)

    file = open('output.txt', 'w', newline = '')
    file.write(str(Decimal(pi)))
    file.close()
    print("Done.")

    #return pi

chudnovskyBig()

第 2 步:我打开此文件并使用正则表达式查找某个字符串的所有匹配项。

import re

file = open('output.txt', 'r')

lines = file.read()

regex = input("Enter Combination: ")
match = re.findall(regex, lines)
print('Matches found: ' + str(len(match)))
file.close()
input("Press Enter to Exit.")

如何更改我的查找所有匹配项代码以查看包含许多这些组合(每行一个)而不是一次仅一个组合的 csv 文件?

csv文件格式:

1\t2\t3\t4\t5\t6\r\n ..我想?

1

【问题讨论】:

  • match = re.findall(regex, lines) 中的正则表达式变量应该是您要匹配的正则表达式模式,例如 '[A-Za-z0-9-]+' 。目前,您有一个输入字符串。将正则表达式变量更改为您想要匹配的模式并更改行和正则表达式,以便行是您的输入字符串而不是文件内容。

标签: python regex csv python-3.x io


【解决方案1】:

这是一个如何使用 re.findall 的示例

import re
pattern = '[A-Za-z0-9-]+' # pattern for matching all ASCII characters, digits, and repetitions of
                            # them (+)
lines = "property"           # adding input string, raw_input("Enter Combination: ")
ls = re.findall(pattern,lines)
print ls

【讨论】:

    【解决方案2】:

    我相信你应该使用该方法:

    re.findall(模式,字符串);

    更多信息在这里:

    How can I find all matches to a regular expression in Python?

    由于搜索词“匹配”和“正则表达式”返回了大量不相关的链接,因此上述链接并不容易追踪。

    【讨论】: