检查文件名是否包含字符串Python

时间:2013-07-04 14:42:47

标签: python

我试图找到一种方法,如果它包含如下所示的任何字符串,将检查程序正在读取的文件的名称。我不确定这是否是正确的方法。该字符串将成为一个全局变量,因为我必须稍后在程序中使用它

class Wordnet():

    def __init__(self):
        self.graph = Graph()
        self.filename = ''
        self.word_type = ''

    def process_file(self):
        self.filename = "noun.txt"
        self.file = open(self.filename, "r")
        return self.file, self.filename

    def check_word_type(self, filename):
        if 'noun' in filename:
            self.word_type = 'noun'
        elif 'verb' in filename:
            self.word_type = 'verb'
        elif 'vrb' in filename:
            self.word_type = 'verb'
        elif adj in filename:
            self.word_type = 'adj'
        elif adv in filename:
            self.word_type = 'adv'
        else:
            self.word_type = ''
        return self.word_type

if __name__ == '__main__':
    wordnet = Wordnet()
    my_file = wordnet.process_file()  
    print wordnet.word_type

任何帮助都会很棒

2 个答案:

答案 0 :(得分:9)

试试这个:

def check_word_type(self, filename):
    words = ['noun','verb','vrb','adj','adv'] #I am not sure if adj and adv are variables
    self.word_type = ''
    for i in words:
        if i in filename:
            self.word_type = str(i) #just make sure its string

    return self.word_type

答案 1 :(得分:1)

您没有在任何地方致电check_word_type()。尝试:

def process_file(self):
    self.filename = "noun.txt"
    self.file = open(self.filename, "r")
    self.check_word_type(self, self.filename)
    return self.file, self.filename