python - ValueError: int() 以 10 为底的无效文字:'-f'
问题描述
这是一个关于如何在 Jupyter Notebook 中使用命令行仅通过文件名和一些类似这样的输入来运行代码的示例ipython RollDie.py 600
。
我自己编写了代码并拿了在线示例并尝试运行两者,但它一直给我同样的错误说ValueError: invalid literal for int() with base 10: '-f'
。错误在第 9 行,因为int(sys.argv[1]))
我试图将其转换为 float 然后 int 但它只是说could not convert string to float: '-f'
。
我为我的案例搜索了很多解决方案,但没有找到像这样的方法,只是找到了一种我应该编写一种方法来读取文件的方法(我是新来处理编码中的文件),但是他的例子中的书想在编写代码后创建文件并且没有提到这个错误的任何内容。
注意:argv[0]
是字符串'RollDie.py'
,argv[1]
应该是输入字符串'600'
,因此转换argv[1]
为 int 应该没有问题。
书名是《Python for Programmers》。
编码:
"""Graphing frequencies of die rolls with Seaborn."""
import matplotlib.pyplot as plt
import numpy as np
import random
import seaborn as sns
import sys
# use list comprehension to create a list of rolls of a six-sided die
rolls = [random.randrange(1, 7) for i in range(int(float(sys.argv[1])))] # Range is written that way so we can modify the code with the command line directly and no need to rund the code by yourself(A pro gamer move).
# NumPy unique function returns unique faces and frequency of each face
values, frequencies = np.unique(rolls, return_counts=True)
title = f'Rolling a Six-Sided Die {len(rolls):,} Times'
sns.set_style('whitegrid') # white backround with gray grid lines
axes = sns.barplot(values, frequencies, palette='bright') # create bars
axes.set_title(title) # set graph title
axes.set(xlabel='Die Value', ylabel='Frequency') # label the axes
# scale y-axis by 10% to make room for text above bars
axes.set_ylim(top=max(frequencies) * 1.10)
# display frequency & percentage above each patch (bar)
for bar, frequency in zip(axes.patches, frequencies):
text_x = bar.get_x() + bar.get_width() / 2.0
text_y = bar.get_height()
text = f'{frequency:,}\n{frequency / len(rolls):.3%}'
axes.text(text_x, text_y, text,
fontsize=11, ha='center', va='bottom')
plt.show() # display graph
%save RollDie.py 1
解决方案
当您运行代码时,似乎-f
是 sys.argv[1],这就是您收到错误的原因(当然,您不能转换-f
为浮点数或字符串)。您在运行文件时是否明确说明了这一点?不确定,比如:
ipython RollDie.py -f 600
如果不是,它可能与某种类型的未显示的内置命令有关。您是否尝试过使用 python 而不是 ipython?
推荐阅读
- intellij-idea - 在不影响 vue 模板的情况下,使用 intellij 从 HTML 中的标签周围更改“小于”和“大于”的颜色
- python - 事件编码键盘输入
- python - 在后端实现 facebook 类型更简单的“喜欢”功能
- r - R:当两个事件(列)都为真时,参考其中一个来决定值
- rstudio - 删除 R studio 中的第一行错误的维度数不正确
- java - 在我用 Java 杀死它的持有者后,一个对象还活着吗?
- angular-cli - 运行“ng update”的任何变体都会触发此错误:“connect ETIMEDOUT 104.18.97.96:443”
- ruby-on-rails - Rails 5、Nginx、Puma、Rails 管理员 - ERR_TOO_MANY_REDIRECTS
- c++ - 通过 QML 仿函数对 C++ 模型进行排序和过滤?
- c# - 使用 eBUS SDK 和 EmguCV 在 C# 中从 PvBuffer 创建一个 Mat