【发布时间】:2018-01-21 08:29:12
【问题描述】:
我有这个文件pluralizer.py,其中包含使用re 模块的函数和类:
from re import *
def pluralize(noun, funcs):
for matches_rule, apply_rule in funcs:
if matches_rule(noun):
return apply_rule(noun)
raise ValueError("no matching rule for {0}".format(noun))
def build_match_and_apply_functions(pattern, search, replace):
def matches_rule(word):
return re.search(pattern, word)
def apply_rule(word):
return re.sub(search, replace, word)
return (matches_rule, apply_rule)
class LazyRules:
rules_filename = 'rules.txt' #a class variable - shared across all instances of the LazyRules class
def __init__(self):
self.pattern_file = open(self.rules_filename, encoding="utf-8")
self.cache=[]
def __iter__(self):
self.cache_index=0
return self #returning self signals that this class defines a __next__ method
def __next__(self):
self.cache_index += 1
if len(self.cache) >= self.cache_index:
return self.cache[self.cache_index-1]
if self.pattern_file.closed:
raise StopIteration
line = self.pattern_file.readline()
if not line: #if there's a line to read, it will not be an empty string (even if new row, it will be "\n")
self.pattern_file.close()
raise StopIteration
pattern,search,replace= line.split(None,3)
funcs = build_match_and_apply_functions(pattern,search,replace)
self.cache.append(funcs) # before returning the match&apply functions, we save them in the list self.cache
return funcs
还有数据文件rules.txt:
[sxz]$ $ es
[^aeioudgkprt]h$ $ es
[^aeiou]y$ y$ ies
$ $ s
它应该工作的方式是:
import pluralizer
funcs = pluralizer.LazyRules()
p = pluralizer.pluralize("baby", funcs)
预期的输出是"babies",但我得到:
NameError: name 're' is not defined
将import re 放在pluralize 函数中也不起作用。 re 模块为什么“拒绝”导入?我搜索了旧问题,但没有找到答案,如果我忽略了它,对不起。谢谢!
【问题讨论】:
-
尝试
import re而不是from re import *,因为后者会将re中的所有内容导入当前命名空间,而不是re.<methods> -
我也试过了,但不幸的是,这给了我同样的错误。 :(
-
您将
import re放在pluralizer.py的开头,而不是放在pluralize函数中。 -
这就是我所做的,但它仍然“未定义”。我完全感到困惑......
-
发布整个堆栈跟踪,(包括文件位置)
标签: python file python-import import-module