Regex FindAll occurances of a string inside a text file. How?
csv, io, python, python-3.x, regex
Solution
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
Problem
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