检查文件名是否包含字符串 Python
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17473093/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Check if the filename contains a string Python
提问by Johnnerz
I am trying to find a way where the name of the file the program is reading will be checked if it contains any of the strings like below. I am not sure if that is the right way to go about it. The string is going to be a global variable as I have to use it later in the program
我试图找到一种方法来检查程序正在读取的文件的名称是否包含如下所示的任何字符串。我不确定这是否是正确的方法。该字符串将成为一个全局变量,因为我稍后必须在程序中使用它
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
Any help would be great
任何帮助都会很棒
采纳答案by xlharambe
Try this:
尝试这个:
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
回答by mishik
You are not calling check_word_type()
anywhere. Try:
你不是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