Hello im a beginner to python,
I’m iterating through a csv file and trying to find out how many times a specific user uses the symbols: "@" and "#" and printing it out as a dictionary. The issue is I think its counting something like "@yomomma" as a non factor since the symbol isn’t sperate from the word, but im also not sure.
def getUserTweetDetails(tweetFile,twitterUsername):
import csv
myFile = open(tweetFile,"r") # opening file in read
csvReader = csv.reader(myFile,delimiter=",") # splitting for ','
next(csvReader) # skipping header
userDetails = {}
mentionsCounter = 0
hashtagCounter = 0
for row in csvReader:
if (row[0] == twitterUsername):
if (row[2] == '@'):
mentionsCounter += 1
if (row[2] == '#'):
mentionsCounter += 1
userDetails["mentions"] = mentionsCounter
userDetails["hashtags"] = hashtagCounter
print(userDetails)
This returns
getUserTweetDetails("Tweets-2020 (2).csv",'ChrisMurphyCT')
**{'mentions': 0, 'hashtags': 0}**
The csv files format looks like this: twitterUsername,politicalParty,tweetText
>Solution :
The issue with your code is that you are checking if the third element in the row is equal to ‘@’ or ‘#’, but the third element in the row is the tweet text, not the symbol itself. To fix this, you can use the .count() method to count the number of times the symbol appears in the tweet text.
def getUserTweetDetails(tweetFile,twitterUsername):
import csv
myFile = open(tweetFile,"r") # opening file in read
csvReader = csv.reader(myFile,delimiter=",") # splitting for ','
next(csvReader) # skipping header
userDetails = {}
mentionsCounter = 0
hashtagCounter = 0
for row in csvReader:
if (row[0] == twitterUsername):
# Count the number of mentions in the tweet text
mentionsCounter += row[2].count('@')
# Count the number of hashtags in the tweet text
hashtagCounter += row[2].count('#')
userDetails["mentions"] = mentionsCounter
userDetails["hashtags"] = hashtagCounter
print(userDetails)
With this updated code, the mentionsCounter and hashtagCounter variables will be incremented by the number of times the ‘@’ and ‘#’ symbols appear in each tweet text, respectively. This will allow you to accurately count the number of mentions and hashtags used by the specified user.
You can then call the getUserTweetDetails() function as follows:
getUserTweetDetails("Tweets-2020 (2).csv",'ChrisMurphyCT')
This will print a dictionary containing the number of mentions and hashtags used by the user ‘ChrisMurphyCT’ in the specified CSV file.