Ich erstelle eine Hauptfunktion, die durch ein Wörterbuch, das einen Schlüssel für alle damit verbundenen Werte hat, durchläuft. Ich habe Probleme, weil ich das Wörterbuch nicht in Kleinbuchstaben schreiben kann. Ich habe versucht, zu verwenden, aber ohne Erfolg. Außerdem sollte das Programm die Wörter des Satzes betrachten, bestimmen, ob es mehr dieser Wörter in Sätzen gesehen hat, die der Benutzer zuvor "glücklich", "traurig" oder "neutral" genannt hat (basierend auf den drei Wörterbüchern). und raten Sie, welche Marke auf den Satz angewendet werden soll.Looping durch ein Wörterbuch in Python
wäre ein Beispiel Ausgabe wie
seinSentence: i started screaming incoherently about 15 mins ago, this is B's attempt to calm me down.
0 appear in happy
0 appear in neutral
0 appear in sad
I think this is sad.
You think this is: sad
Okay! Updating.
Code:
import csv
def read_csv(filename, col_list):
"""This function expects the name of a CSV file and a list of strings
representing a subset of the headers of the columns in the file, and
returns a dictionary of the data in those columns, as described below."""
with open(filename, 'r') as f:
# Better covert reader to a list (items represent every row)
reader = list(csv.DictReader(f))
dict1 = {}
for col in col_list:
dict1[col] = []
# Going in every row of the file
for row in reader:
# Append to the list the row item of this key
dict1[col].append(row[col])
return dict1
def main():
dictx = read_csv('words.csv', ['happy'])
dicty = read_csv('words.csv', ['sad'])
dictz = read_csv('words.csv', ['neutral'])
dictxcounter = 0
dictycounter = 0
dictzcounter = 0
a=str(raw_input("Sentence: ")).split(' ')
for word in a :
for keys in dictx['happy']:
if word == keys:
dictxcounter = dictxcounter + 1
for values in dicty['sad']:
if word == values:
dictycounter = dictycounter + 1
for words in dictz['neutral']:
if word == words:
dictzcounter = dictzcounter + 1
print dictxcounter
print dictycounter
print dictzcounter
Wenn 'col_list' eine Liste von _one_ string ist, muss dieser Ausdruck wegen des Entpackungsfehlers abstürzen:' dict1 = dict ((k, v.lower()) für k, v in col_list) '. Sind Sie sicher, dass Sie uns den richtigen Code zeigen? Die gleiche Anweisung überschreibt auch das Wörterbuch, das Sie in der Schleife erstellt haben. Dies erklärt wahrscheinlich, warum Ihr Code nicht wie erwartet funktioniert. – DyZ
Was Sie an 'read_csv' übergeben _is_ eine Liste mit einem String:' ['happy'] '. Und diese Liste wird zum Wert des Formalparameters 'col_list'. – DyZ
Ich weiß nicht, was Sie mit >>> meinen, aber wie Ihr Programm jetzt geschrieben ist, 'col_list' ist eine Liste von einem String. – DyZ