步骤1:我生成25位小数的圆周率,并将其保存到output.txt文件中。
步骤2:我打开这个文件,并使用正则表达式查找所有特定字符串的匹配项。
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