I'm trying to build a 'database' of words and their corresponding tweet identifier.
My guess is that a dictionary is the best option for doing this.
Identifier, user, text, words get split on tab.
Example of input :
1035421931321864192 SchipholWatch RT @vinvanoort: Zo, ik heb getekend Genoeg #geschiphol, hoogste tijd voor een eerlijk en duurzaam #luchtvaartbeleid RT @vinvanoort : Zo , ik heb getekend Genoeg #geschiphol , hoogste tijd voor een eerlijk en duurzaam #luchtvaartbeleid
1035421930541772800 ev4uam2 RT @AfshinEllian1: Kennelijk vinden ze daar aan die gezellige tafel normaal dat steltje barbaren onze grondwettelijke rechten bedreigen. Zouden we ook voor andere buitenwettelijke dreigingen moeten capituleren? Wat een door ons gesubsidieerde domheid! #laatop1 #cartoonwedstrijd RT @AfshinEllian1 : Kennelijk vinden ze daar aan die gezellige tafel normaal dat steltje barbaren onze grondwettelijke rechten bedreigen . Zouden we ook voor andere buitenwettelijke dreigingen moeten capituleren ? Wat een door ons gesubsidieerde domheid ! #laatop1 #cartoonwedstrijd
Example of desired output:
{'exampleword' : ['1035421930541772800', '1235424930545772800']}
Current code :
def main():
olist = []
worddict = {}
for line in sys.stdin:
i,u,t,w = line.split('\t')
splitword = w.split()
olist.extend(splitword)
for num,name in enumerate(olist):
print("{} [{}]".format(name.strip(), num))
main()
So far i have tried iterating over the lines and adding splitword + i(which is the tweet identifier) to a dictionary, without succes.
Basically what you want is to "reverse" a dictionary with list
values to another dictionary with list
values.
I abstracted from the actual tweet data since that would obfuscate the actual problem's answer.
A greedy implementation could be:
import collections
def reverse_dict(input):
output = collections.defaultdict(list)
for key, val in input.items():
for item in val:
output[item].append(key)
return output
def main():
input = {
'u123': ['hello', 'world'],
'u456': ['hello', 'you'],
'u789': ['you', 'world'],
}
output = reverse_dict(input)
print output
if __name__ == '__main__':
main()
As @Michael Butscher said, the expected output from your question is not a valid Python dictionary. The above code will output:
{'world': ['u789', 'u123'], 'you': ['u789', 'u456'], 'hello': ['u456', 'u123']}
Furthermore, as @Austin answered, approaching this problem using "brute force" won't necessarily be the best solution.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.