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

如何在Python单词计数程序中排除引号内的特定字符串?

Fixing Word Count to Ignore Quoted Content

Hey Jake, let's sort out that word count discrepancy—your current code counts everything split by spaces, including stuff like "--" inside quotes, which is why you're getting 277 instead of the correct 272. Here's how to adjust your program to ignore text within quotes:

The Problem with Your Original Code

Your current approach uses line.split() to count words, which doesn't distinguish between text inside and outside quotes. Any characters separated by spaces (even those inside quotes) get counted as words, hence the extra 5 from the quoted "--" and other quoted terms.

Solution 1: Replace Quoted Content Before Counting

A straightforward way is to strip out all text inside quotes first, then count the remaining words. We can use regular expressions to handle this cleanly:

import re

# Use a with statement to safely open/close the file (better practice than manual close)
with open("Gettysburg.txt", "r") as infile:
    data = infile.read()

# Remove all text enclosed in double quotes (adjust to single quotes if needed)
cleaned_text = re.sub(r'"[^"]*"', '', data)

# Now count words, lines, and characters as before
words = cleaned_text.split()
nwords = len(words)
lines = data.count('\n') + 1  # Add 1 for the last line if it doesn't end with a newline
nchars = len(data)

print("Jake's word calculator.")
print('The number of words is', nwords)

Solution 2: Match Only Words Outside Quotes

If you want to be more precise (and avoid altering the original text for character count), you can use a regex to directly find all words that aren't inside quotes:

import re

with open("Gettysburg.txt", "r") as infile:
    data = infile.read()

# Regex pattern to match words NOT inside double quotes
# \b\w+\b matches standard words; the lookarounds ensure they're not quoted
pattern = r'(?<!")\b\w+\b(?!")'
valid_words = re.findall(pattern, data)

nwords = len(valid_words)
lines = data.count('\n') + 1
nchars = len(data)

print("Jake's word calculator.")
print('The number of words is', nwords)

Notes

  • If your document uses single quotes instead of double quotes, just swap the " in the regex patterns with '.
  • Both solutions should give you the correct 272-word count by excluding any content wrapped in quotes.
  • Using with open(...) is better practice because it automatically closes the file for you, even if an error occurs.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.22 09:31:02