首页 > 解决方案 > 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

标签: pythoncommand-line-argumentssys

解决方案


当您运行代码时,似乎-f是 sys.argv[1],这就是您收到错误的原因(当然,您不能转换-f为浮点数或字符串)。您在运行文件时是否明确说明了这一点?不确定,比如:

ipython RollDie.py -f 600

如果不是,它可能与某种类型的未显示的内置命令有关。您是否尝试过使用 python 而不是 ipython?


推荐阅读