You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在推特CSV数据库统计单词时排除@提及内容?

How to Exclude @ Mentions from Your Word Count in Python

Hey there! Since you're new to Python, let's break this down simply—your current code is a solid start, and we just need to add one small step to filter out those @ mentions.

Here's the revised code, with some improvements and explanations:

# Use a with statement to safely open and read the file (it auto-closes the file for you!)
with open('file_directory', 'r') as file:
    text = file.read()

# Clean up punctuation and make everything lowercase
clean_text = text.replace('.',' ').replace('!',' ').replace('?',' ').replace(';',' ').lower()

# Split into words, then filter out any that start with @
words = [word for word in clean_text.split() if not word.startswith('@')]

print(words)
print(f"Total words (excluding @ mentions): {len(words)}")

# To count your specific query 'lala'
lala_count = words.count('lala')
print(f"For the query 'lala' we have {lala_count}")

Key Changes Explained:

  • with statement: This is a Python best practice—no need to remember to close the file manually, which prevents mistakes.
  • Filtering with list comprehension: The line [word for word in clean_text.split() if not word.startswith('@')] uses a list comprehension—a handy Python shortcut—to check every word in your list. If a word starts with @, it gets skipped; all other words stay in the list. Perfect for excluding mentions!
  • F-strings: I swapped out the old % formatting for f-strings (f"...") because they're easier to read and write—great for new Python learners.

Extra Tips for Twitter Data:

  • If your CSV has multiple columns (like separate columns for usernames, tweet text, etc.), you should use Python's built-in csv module to read only the tweet text column. Let me know if you need help with that!
  • You might also want to exclude URLs (they usually start with http or https). Just add another condition to the filter: if not word.startswith('@') and not word.startswith('http')

Hope this makes sense and helps you get the word count you need. Happy coding!

内容的提问来源于stack exchange,提问作者Tomito

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 08:35:45