下面的文本是一个从原始数据文本文件执行分析的示例。 原始数据的格式是:user1跟随user2 user3 user4。例如,第一行的意思是:托尼跟着汤姆和弗兰克。 因此,托尼是汤姆和弗兰克的追随者
tony tom frank (it means tony follows tom and frank)
tom (it means tom follows no one)
tom tony jordan (it means tom follows tony and jordan)
frank tom tony (it means frank follows tom and tony)
jordan frank (it means jordan follows frank)
tom frank (it means tom follows frank)
Thus
1. tom's followers are tony and frank
2. tony's followers are tom and frank
3. frank's followers are tony and jordan and tom
4. jordan's followers is just tom.
我想计算一个表来分析谁是追随者最多的。 我想得到如下输出:user1 have followers:user2,user3,user4 我试过的代码没有给我一个正确的。有人能帮忙吗
我试过以下方法:
**with open("sample.txt", 'r') as fhand:
aCompleteUserDict = {}
aCompleteUserList = []
for line in fhand:
allUsers = line.split() # This part is to convert each line in the file into a list
for aUser in allUsers[0:]:
aCompleteUserDict[aUser] = allUsers[1:]
#fan = allUsers[0]
print(aCompleteUserDict)**
***The actual output for my try is:***
{'tony': ['tom', 'tony'], 'tom': ['frank'], 'frank': ['frank'], 'jordan': ['frank']}
***My expected output format is:***
{'tony': ['tom', 'frank'], 'tom': ['frank', 'tony']], 'frank': ['tony', 'jordan', 'tom'], 'jordan': ['tom']}
这里有一个解决方案,可以很容易地适应从文件读取
相关问题 更多 >
编程相关推荐