我试图编写一个程序来确定两个单词是否相同。我已经写了两个类:featTup(基本上围绕包含字母的值的元组的包装),和featWord(基本上是featTup物体的周围包装。)Python中的动态类实例命名
(对不起,这是所有这么久!)
下面是一些(希望相关)代码:
class featTup(object):
def __init__(self,char):
self.char = char
self.phone_vals = None
self.dia_vals = None
if self.char in phone_codes:
self.phone_vals = phone_feats[phone_codes.index(char)]
elif self.char in dia_codes:
self.dia_vals = dia_feats[dia_codes.index(char)]
...
class featWord(list):
def do_dia(self,char_feats,dia_feats):
#This method handles the changes diacritics make to preceding phones
for val in dia_feats:
if dia_val:
char_feats.change_val(tup,char_feats.index(dia_val),dia_val)
def get_featWord(self):
return self.word_as_feats
def __init__(self,word):
self.word = word
self.word_as_feats = [featTup(char) for char in self.word]
for char in self.word_as_feats:
if char.is_dia():
i = self.word_as_feats.char_index(char)
self.word_as_feats.do_dia(self.word_as_feats[i-1],self.word_as_feats[i])
def word_len(self):
return len(self.get_featWord())
def char_index(self,char):
return self.word_as_feats.index(char)
的问题是,我想借此单词列表和使featWord对象为所有的人。我不知道每个列表会有多长时间,也不知道每个单词有多少个字符。 更多代码:
def get_words(text1,text2):
import codecs
textin1 = codecs.open(text1,encoding='utf8')
word_list1 = textin1.readlines()
textin1.close()
textin2 = codecs.open(text2,encoding='utf8')
word_list2 = textin2.readlines()
textin2.close()
print word_list1,word_list2
fixed_words1 = []
fixed_words2 = []
for word in word_list1:
fixed_word = word.replace('\n','')
fixed_words1.append(fixed_word)
for word in word_list2:
fixed_word = word.replace('\n','')
fixed_words2.append(fixed_word)
print fixed_words1,fixed_words2
words1 = [(featWord(word)) for word in fixed_words1]
words2 = [(featWord(word)) for word in fixed_words2]
# for word1 in fixed_words1:
# for x in xrange(len(fixed_words1)):
words1.append(featWord(word))
for word2 in fixed_words2:
#for x in xrange(len(fixed_words2)):
words2.append(featWord(word))
print words1
#words1 = [featWord(word) for word in fixed_words1]
#words2 = [featWord(word) for word in fixed_words2]
return words1,words2
def get_cog_dict(text1,text2,threshold=10,print_results=True):
#This is the final method, running are_cog over all words in
#both lists.
word_list1,word_list2 = get_words(text1,text2)
print word_list1, word_list2
目前的情况是,当我打电话或者最后两个方法,我得到空列表名单;当我从字符串实例化新的featWord对象时,我只给它(例如x = featWord(“十”)或其他),它工作正常。相关的事情是,特技似乎返回一个空列表,而不是(当我从IDLE实例化featWord,如上所述,它返回作为featTup实例列表,这是很好的)。我不确定为什么/如果那是问题。
在我看来,我的问题(至少部分)是由于不适当地初始化功能词。我正在构建它们,或者其他什么,但没有分配它们的名字。我已经尝试过所有我能想到的事情(如注释部分所证明的),而且我很难过。这里有关于使用字典命名类实例等的答案,但由于我无法预先定义字典(每个单词和单词列表可能有不同的长度),我不知道该怎么做。
任何帮助将非常感激。我有点在这里疯狂。谢谢。
请准确地缩进您的代码(即您在自己的代码中使用相同的方式) - 它不会运行。 ETA:无视这一点,@KarlKnechtel修复了它! –
@DavidRobinson花了几次尝试;我想我现在拥有它。 –
无论如何,你的**问题到底是什么**?你能显示样本输入和预期的相应输出吗?你能展示实际发生的事情吗?你能给我们一个没有所有评论的东西的版本,显示你目前正在尝试的东西吗?或者至少组织你对企图的描述更好? –