为什么我的代码未在我的代码中执行for循环?

时间:2019-10-02 04:18:15

标签: python csv for-loop pycharm

我创建了一个函数和一个for循环,其中for循环与该函数没有任何关系。执行代码时,将跳过for循环。我想知道为什么会这样。

我有一个TSV情感文本文件,其标题为:“正字数”,“负字数”,“总字数”和“文本”。创建一个函数来查找平均单词数,并使用for循环对每个句子进行分类,然后将“文本”附加到名称与分类结果匹配的数组中。当我没有调用函数时,代码按预期运行,而是将计算集成在for循环中。但是,我需要知道为什么会这样,因为我可能无法解决像这样的每个问题。

def get_sentiment_category(p_value, n_value): #has more classification, minimalize
        if p_value is not 0 and n_value is 0:
            return("positive")
        elif p_value is 0 and n_value is not 0:
            return("negative")
def get_average_word(data):
    total_word = 0
    total_sentence = 0
    for line in data:
        total_sentence += 1
        total_word = total_word + int(line[2])
    return (total_word/total_sentence)
list_of_category = ["positive","negative"] ## Declare category name
positive = []
negative = []

with open(file, "r", encoding="utf-8-sig") as source:
    source_read = csv.reader(source, delimiter='\t') #reading tsv
    next(source_read, None)#skip header 

    average_word = get_average_word(source_read) ## getting average word
    print("get avg")

    for line in source_read:
        print("1212")
        p_value = int(line[0]) ## positive value
        n_value = int(line[1]) ## negative value
        category = get_sentiment_category(p_value,n_value)
        globals()[category].append(line[3]) ## if category == "positive", line[3](text) will be append to array with name "positive"

print(average_word)
for item in list_of_category:
    print(globals()[item]) 
    print("-----------")
Sample data:
positive'''negative''' word_count''' text
0''''''''''1'''''''''''3'''''''''''''I am sad
1''''''''''0'''''''''''4'''''''''''''I am very happy

## I do not know to to display TSV, forgive me

输出应为:

get avg
1212
1212
3.5
["I am sad"]
-----------
["I am very happy"]
-----------

相反:

get avg
3.5
[]
-----------
[]
-----------

0 个答案:

没有答案