3

Step 1: I generate 25 decimal digits of Pi and save it to output.txt file.

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()

Step 2: I Open this file and use regex to find all matches of a certain string.

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.")

How can I change my find all matches code to look at a csv file with many of these combinations(one per line) instead of just one at the time?

Format of csv file:

1\t2\t3\t4\t5\t6\r\n ..i think?

1

suchislife
  • 4,251
  • 10
  • 47
  • 78
  • Your regex variable in match = re.findall(regex, lines) should be the regex pattern that you want to match, for instance '[A-Za-z0-9-]+' . At the moment you have an input string instead. Change the regex variable to the pattern you want to match and change lines and regex so that lines is your inputstring instead of the file content. – user1749431 Feb 23 '14 at 18:34

2 Answers2

4

Here's an example of how you can use 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
user1749431
  • 559
  • 6
  • 21
1

I believe you should use the method:

re.findall(pattern,string);

More info here:

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

And the above link wasn't easy to track down due to the search terms "matches" and "regex" returning a plethora of irrelevant links.

Community
  • 1
  • 1
Gi0rgi0s
  • 1,757
  • 2
  • 22
  • 31