<p>谢谢你更新你的问题。首先,我要定义程序的入口点,例如<code>main</code>。然后,只需进行初步的CSV(非常简单)解析即可。这只是打印有关CSV中每个条目的信息,以验证我们是否正确解析它:</p>
<pre><code>def main():
with open("project_twitter_data.csv", "r") as file:
# Skip the first line
next(file)
for tweet, retweet_count, reply_count in map(lambda line: line.strip().split(","), file):
print(f"tweet: {tweet[:20]}...\nretweet_count: {retweet_count}\nreply_count: {reply_count}\n")
if __name__ == "__main__":
main()
</code></pre>
<p>输出:</p>
<pre><code>tweet: @twitteruser: On now...
retweet_count: 3
reply_count: 0
tweet: BUNCH of things abou...
retweet_count: 1
reply_count: 0
>>>
</code></pre>
<p>我的CSV文件中只有两个条目,但它应该适用于任意数量的条目(只要推文中没有逗号)</p>
<p>然后,你需要加载你的积极和消极的话。我假设文件不是太大,所以你可以把所有单词都读入列表。有许多不同的方法可以计算每条推文的正面和负面词汇。例如,您可以将当前推文拆分为空白,以获得“单词”列表。我之所以说“单词”,是因为从技术上讲,这些字符串可能包含标点符号,所以您必须以某种方式将其考虑在内。另一种方法是使用带有单词边界的正则表达式模式从当前tweet生成单词列表。我在下面所做的只是在当前tweet中寻找一个子串,这有点幼稚。除非有一个适当的单元测试,故意寻找以确保没有使用这种方法,否则这应该足够好了</p>
<pre><code>def main():
with open("positive_words.txt", "r") as file:
positive_words = file.read().splitlines()
with open("negative_words.txt", "r") as file:
negative_words = file.read().splitlines()
with open("project_twitter_data.csv", "r") as file:
# Skip the first line
next(file)
for tweet, retweet_count, reply_count in map(lambda line: line.strip().split(","), file):
positive_count = sum(tweet.count(word) for word in positive_words)
negative_count = sum(tweet.count(word) for word in negative_words)
net_count = positive_count - negative_count
# Write retweet_count, reply_count, positive_count, negative_count and net_count to resulting_data.csv
if __name__ == "__main__":
main()
</code></pre>