第1步:我生成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 ..我覺得呢?
你的正則表達式變量匹配= re.findall(正則表達式,行)應該是要匹配的正則表達式模式,比如一個例子「[ A-Za-z0-9 - ] +'。此刻你有一個輸入字符串。將regex變量更改爲要匹配的模式,並更改行和正則表達式,以便行是您的輸入字符串而不是文件內容。 – user1749431