[英]How do I create a list of all occurances of a string which ends with a specific file type found in a text file?
[英]Regex FindAll occurances of a string inside a text file. How?
步驟1:我生成Pi的25個十進制數字並將其保存到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:我打開此文件,並使用regex查找某個字符串的所有匹配項。
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
相信您應該使用以下方法:
re.findall(圖案,字符串);
更多信息在這里:
由於搜索字詞“ matches”和“ regex”返回了大量不相關的鏈接,因此上述鏈接很難找到。
這是一個如何使用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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.