How to run a module
Posted
by
Jimmy
on Stack Overflow
See other posts from Stack Overflow
or by Jimmy
Published on 2012-09-01T03:27:57Z
Indexed on
2012/09/01
3:37 UTC
Read the original article
Hit count: 147
python
I have a module file containing the following functions:
def replace(filename):
match = re.sub(r'[^\s^\w]risk', 'risk', filename)
return match
def count_words(newstring):
from collections import defaultdict
word_dict=defaultdict(int)
for line in newstring:
words=line.lower().split()
for word in words:
word_dict[word]+=1
for word in word_dict:
if'risk'==word:
return word, word_dict[word]
when I do this in IDLE:
>>> mylist = open('C:\\Users\\ahn_133\\Desktop\\Python Project\\test10.txt').read()
>>> newstrings=replace(mylist) ### This works fine.
>>> newone=count_words(newstrings) ### This leads to the following error.
I get the following error:
Traceback (most recent call last):
File "<pyshell#134>", line 1, in <module>
newPH = replace(newPassage)
File "C:\Users\ahn_133\Desktop\Python Project\text_modules.py", line 56, in replace
match = re.sub(r'[^\s^\w]risk', 'risk', filename)
File "C:\Python27\lib\re.py", line 151, in sub
return _compile(pattern, flags).sub(repl, string, count)
TypeError: expected string or buffer
Is there anyway to run both functions without saving newstrings
into a file, opening it using readlines()
, and then running count_words
function?
© Stack Overflow or respective owner