需要帮助调试我的 python 代码,它很糟糕
我正在使用 Python 2.7x,但在调试时遇到问题。我不太确定我能做什么。任何帮助表示赞赏。谢谢。
import re
import sys
# Grab parameters from the command line
(filename, threshold) = sys.argv[1:3]
# Validate arguments
if (re.match("\D", threshold)):
print "The threshold must be a number."
sys.exit(1)
# Read file and tally word frequencies
fh = open(filename)
file = fh.read()
words = []
for line in file.split('\n'):
found = 0
for word in words:
if word[0] == line.lower():
found = 1
word[1] += 1
# initialize a new word with a frequency of 1
if found == 0:
words.append([line, 1])
# Print words and their frequencies, sorted alphabetically by word. Only print a word if its frequency is greater than or equal to the threshold.
for word in sorted(words):
if word[0] < threshold: continue
print "%4d %s" % (word[1], word[0])
I'm using Python 2.7x and am having trouble debugging it. I'm not really sure what I can do. Any help is appreciated. Thanks.
import re
import sys
# Grab parameters from the command line
(filename, threshold) = sys.argv[1:3]
# Validate arguments
if (re.match("\D", threshold)):
print "The threshold must be a number."
sys.exit(1)
# Read file and tally word frequencies
fh = open(filename)
file = fh.read()
words = []
for line in file.split('\n'):
found = 0
for word in words:
if word[0] == line.lower():
found = 1
word[1] += 1
# initialize a new word with a frequency of 1
if found == 0:
words.append([line, 1])
# Print words and their frequencies, sorted alphabetically by word. Only print a word if its frequency is greater than or equal to the threshold.
for word in sorted(words):
if word[0] < threshold: continue
print "%4d %s" % (word[1], word[0])
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
一般来说,使用
pdb
模块调试 Python 代码是最简单的。将以下代码放置在您希望调试器启动的位置:您可以使用
n
执行下一行代码,使用s
单步执行函数,使用p< /code> 打印一个值(例如,
p Words
将打印您的单词列表)。如果没有有关该问题的更多信息,我真的无法知道您的代码发生了什么,但看来您可能遇到了不一致情况的问题。当您向单词列表中添加某些内容时,应该将其变为小写。
此外,您将字符串与阈值进行比较,而不是数字。应该是:
我希望这有帮助。
In general, debugging Python code is easiest with the
pdb
module. Place the following code where you want the debugger to start:You can use
n
to execute the next line of code,s
to step into functions, andp
to print a value (e.g.,p words
will print your words list).I can't really know what's going on with your code without more information on the problem, but it appears you might be having an issue with inconsistent cases. When you add something to the word list, you should put it in lower case.
Also, you're comparing a string to the threshold, not a number. It should be:
I hope this helps.