Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
This is an example how to search for strings in a text file using Python 3
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
'''
Program: koalition.py
Author: Bodo Schönfeld
Email: python@bodo-schoenfeld.de
Version: 1.0
Python 3.6
Date created: 14/02/2018
'''
import re
import argparse
FILE_NAME = 'koalitionsvertrag.txt' # <- Enter your file here.
try:
file_handle = open(FILE_NAME)
except:
print('File cannot be opened:', FILE_NAME)
exit()
def find_word(input_word):
for line in file_handle:
line = line.rstrip()
# x = re.findall(input_word, line)
x = re.findall(input_word + '[^ ]*', line) # <- define your regex here
for w in x:
di[w] = di.get(w, 0) + 1
# print(di)
return di
def main():
parser = argparse.ArgumentParser()
parser.add_argument('-w', type=str, default='SPD', \
help='add the string you want to search for')
args = parser.parse_args()
result = find_word(args.w)
print('')
for word, count in result.items():
print('Searched word: {}\nCount: {}'.format(word, count))
if __name__ == '__main__':
di = dict()
main()
print('')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.