python - 从模块内导入模块

时间:2018-01-21 08:29:12

标签: python file python-import import-module

我有这个文件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模块'拒绝'导入?我搜索了旧问题,但没有找到答案,对不起,如果我忽略了它。谢谢!

P.S。代码来自'Dive Into Python 3' by Mark Pilgrim

1 个答案:

答案 0 :(得分:0)

为我工作如下,在运行它之前,请确保在python shell中更改工作目录

import os
os.chdir('whatever your working directory and files are')

“ lazyrules.py”文件中的代码如下:

import re
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)

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

class LazyRules:
    rules_filename = 'plural6-rules.txt'

    def __init__(self):
        self.pattern_file = open(self.rules_filename, encoding='utf-8')
        self.cache = []

    def __iter__(self):
        self.cache_index = 0
        return self

    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:
            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)
        return funcs

rules = LazyRules()