一道python的题目,求大神解答
fo.txtthisisthefirstlinethisisthesecondlinethisisthethirdlinethisistheforthlinethisis...
fo.txt
this is the first line
this is the second line
this is the third line
this is the forth line
this is the fifth line
this is the sixth line
this is the seventh line
/////////
///////////我的代码:
def invertWordDict(fileName):
inputFile = open(fileName, 'r')
list1 = [ ]
dict1 = { }
dict2=[]
for line in inputFile:
line=line.strip('\n')
line=line.lower()
list1.append(line)
if ' ' in list1:
list1.remove('')
list1 = [word for line in list1 for word in line.split('!')]
list1 = [word for line in list1 for word in line.split('?')]
list1 = [word for line in list1 for word in line.split('.')]
list1 = [word for line in list1 for word in line.split()]
flag=1
for word in list1:
if word in dict1:
dict1[word] += 1
else:
dict1[word] = 1
return dict1
我的代码是输出 {‘this’:7 , 'is': 7, 'the':7 ,'first':1, 'second':1, 'third':1, 'forth':1,'fifth':1 ,'sixth':1, 'seventh':1, 'line':3}
(就是把每一个单词都编入字典,然后字典里显示每一个单词的个数)
但是如何在字典里每一项倒过来,并且归在一起,来实现:
{7:[‘this’,'is','the'],1:['first','second','third','forth','fifth','sixth','seventh'],3['line']}
要怎样继续编下去,能提供解决的思路和代码吗 展开
this is the first line
this is the second line
this is the third line
this is the forth line
this is the fifth line
this is the sixth line
this is the seventh line
/////////
///////////我的代码:
def invertWordDict(fileName):
inputFile = open(fileName, 'r')
list1 = [ ]
dict1 = { }
dict2=[]
for line in inputFile:
line=line.strip('\n')
line=line.lower()
list1.append(line)
if ' ' in list1:
list1.remove('')
list1 = [word for line in list1 for word in line.split('!')]
list1 = [word for line in list1 for word in line.split('?')]
list1 = [word for line in list1 for word in line.split('.')]
list1 = [word for line in list1 for word in line.split()]
flag=1
for word in list1:
if word in dict1:
dict1[word] += 1
else:
dict1[word] = 1
return dict1
我的代码是输出 {‘this’:7 , 'is': 7, 'the':7 ,'first':1, 'second':1, 'third':1, 'forth':1,'fifth':1 ,'sixth':1, 'seventh':1, 'line':3}
(就是把每一个单词都编入字典,然后字典里显示每一个单词的个数)
但是如何在字典里每一项倒过来,并且归在一起,来实现:
{7:[‘this’,'is','the'],1:['first','second','third','forth','fifth','sixth','seventh'],3['line']}
要怎样继续编下去,能提供解决的思路和代码吗 展开
1个回答
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询
广告 您可能关注的内容 |