相关疑难解决方法(0)

ValueError:基数为10的int()的无效文字:''

我正在创建一个读取文件的程序,如果文件的第一行不是空白,则会读取接下来的四行.在这些行上执行计算,然后读取下一行.如果该行不为空,则继续.但是,我收到此错误:

ValueError: invalid literal for int() with base 10: ''.

它正在读取第一行但不能将其转换为整数.

我该怎么做才能解决这个问题?

代码:

file_to_read = raw_input("Enter file name of tests (empty string to end program):")
try:
    infile = open(file_to_read, 'r')
    while file_to_read != " ":
        file_to_write = raw_input("Enter output file name (.csv will be appended to it):")
        file_to_write = file_to_write + ".csv"
        outfile = open(file_to_write, "w")
        readings = (infile.readline())
        print readings
        while readings != 0:
            global count
            readings = int(readings)
            minimum = (infile.readline())
            maximum = (infile.readline())
Run Code Online (Sandbox Code Playgroud)

python

252
推荐指数
7
解决办法
118万
查看次数

在Windows上设置Python的语言环境的正确方法是什么?

我正在尝试以区域设置感知的方式对字符串列表进行排序.我已经将Babel库用于其他与i18n相关的任务,但它不支持排序.Python的locale模块提供了一个strcoll函数,但需要将进程的语言环境设置为我想要使用的语言环境.有点痛,但我可以忍受它.

问题是我似乎无法实际设置区域设置.该文件locale模块给出了这样的例子:

import locale
locale.setlocale(locale.LC_ALL, 'de_DE')
Run Code Online (Sandbox Code Playgroud)

当我运行时,我得到了这个:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\Python26\Lib\locale.py", line 494, in setlocale
locale.Error: unsupported locale setting
Run Code Online (Sandbox Code Playgroud)

我究竟做错了什么?

python windows localization internationalization

76
推荐指数
6
解决办法
8万
查看次数

67
推荐指数
6
解决办法
13万
查看次数

49
推荐指数
3
解决办法
6万
查看次数

使用Python将括在括号(字符串)中的数字转换为负整数(或浮点数)?

在Python中,将括号(字符串)中包含的数字转换为负整数(或浮点数)的最简单方法是什么?

例如,'(4,301)'到-4301,这在会计应用程序中经常遇到.

python

10
推荐指数
3
解决办法
8885
查看次数

使用 atof 转换数字

在 中Python 3.5,我想使用locale.atof以下代码将德语数字字符串转换为浮点数:


import locale
from locale import atof
locale.setlocale(locale.LC_ALL, 'de_DE')

number = atof('17.907,08')
Run Code Online (Sandbox Code Playgroud)

然而,这提出了一个ValueError

ValueError: could not convert string to float: '17.907.08'
Run Code Online (Sandbox Code Playgroud)


为什么?这不就是atof()为了这个而生的吗?

python python-3.5

4
推荐指数
1
解决办法
1万
查看次数

是否有一种简单的方法来替换没有任何内容的逗号?

我正在尝试将字符串列表转换为浮点数,但这不能用1,234.56这样的数字来完成.有没有办法使用string.replace()函数删除逗号所以我只有1234.56?string.replace(',','')似乎不起作用.这是我目前的代码:

fileName = (input("Enter the name of a file to count: "))
print()

infile = open(fileName, "r")
line = infile.read()
split = line.split()
for word in split:
    if word >= ".0":
        if word <= "9":
            add = (word.split())
            for num in add:
                  x = float(num)
                  print(x)
Run Code Online (Sandbox Code Playgroud)

这是我得到的错误:

文件"countFile.py",第29行,在main x = float(num)ValueError:无法将字符串转换为float:'3,236.789'

python

3
推荐指数
1
解决办法
1063
查看次数

Django ValueError:无法将字符串转换为float

即使我把这行放在我的settings.py中:

LANGUAGE_CODE = 'pt-br'

TIME_ZONE = 'America/Sao_Paulo'

USE_I18N = True

USE_L10N = True

USE_TZ = True

DECIMAL_SEPARATOR = ','

DATE_INPUT_FORMATS = ['%d/%m/%Y']

DATE_FORMAT = r'd/m/Y'
Run Code Online (Sandbox Code Playgroud)

如此处所述:https://docs.djangoproject.com/en/1.10/ref/settings/#decimal-separator

即使将L10N设置为False,它也无法识别(尽管语言代码应该已将小数点分隔符设置为逗号)

Django仍然不会将逗号识别为小数点分隔符

实际错误:

ValueError:无法将字符串转换为float:'123,123'

该字段只是一个默认的FloatField,我没有使用表单.

什么可能导致它无法识别逗号?

这是views.py代码:

def new_object(request):
    data = json.loads(request.body.decode("utf-8"))
    model_name = data.get('model')
    model = apps.get_model(app_label='cadastroimoveis', model_name=model_name)
    obj = model(**data.get('fields'))
    obj.save()
Run Code Online (Sandbox Code Playgroud)

发送的请求只是一个JSON,字段为字符串

编辑:我刚检查,甚至没有DATE_INPUT_FORMATS它工作,它仍然期望默认值

django django-models django-1.10

3
推荐指数
1
解决办法
2050
查看次数

如何解析DataFrame列中的所有值?

DataFrame df有一个名为amount的列

import pandas as pd
df = pd.DataFrame(['$3,000,000.00','$3,000.00', '$200.5', '$5.5'], columns = ['Amount'])
Run Code Online (Sandbox Code Playgroud)

DF:

 ID | Amount
 0  | $3,000,000.00
 1  | $3,000.00
 2  | $200.5
 3  | $5.5
Run Code Online (Sandbox Code Playgroud)

我想解析列量中的所有值并将数量提取为数字并忽略小数点.最终结果是DataFrame,如下所示:

 ID | Amount
 0  | 3000000
 1  | 3000
 2  | 200
 3  | 5
Run Code Online (Sandbox Code Playgroud)

我该怎么做呢?

python pandas

2
推荐指数
1
解决办法
4123
查看次数

将python字符串转换为不带逗号的整数

我正在使用beautifulsoup4从网站中提取价格标签。我使用的代码是这个

 #price
        try:
            price = soup.find('span',{'id':'actualprice'})
            price_result= str(price.get_text())
            print "Price: ",price_result
        except StandardError as e:
            price_result="Error was {0}".format(e)
            print price_result
Run Code Online (Sandbox Code Playgroud)

输出的即时消息是一个字符串,其格式为逗号。例如 82,000,00

我想要的是:

将格式从字符串价格更改为不带逗号的整数价格,以便我可以将它们用作excel中字符串的值

python string beautifulsoup python-2.7 python-3.x

2
推荐指数
1
解决办法
4584
查看次数

仅在两个数字之间替换逗号

我正在尝试用以下情况替换逗号:

123,123  
Run Code Online (Sandbox Code Playgroud)

输出应该是:

123123
Run Code Online (Sandbox Code Playgroud)

为此,我尝试了这个:

re.sub('\d,\d','','123,123')
Run Code Online (Sandbox Code Playgroud)

但那也是删除数字,怎么能避免这个?

我只想重新编写该案例的逗号,这就是我正在使用正则表达式.对于这种情况,例如

'123,123  hello,word'
Run Code Online (Sandbox Code Playgroud)

所需的输出是:

'123123  hello,word'
Run Code Online (Sandbox Code Playgroud)

python regex

1
推荐指数
1
解决办法
1261
查看次数

ValueError:基数为10的int()的无效文字:'11,440'

此代码打印出OS的任务列表.但是,运行时会看到以下错误.这个问题有一个简单的解决方案吗?

  "mem_usage":int(m.group(5).decode('ascii', 'ignore'))})
ValueError: invalid literal for int() with base 10: '11,440'
Run Code Online (Sandbox Code Playgroud)

码:

import re
from subprocess import Popen, PIPE, check_output

def get_processes_running():
    """
    Takes tasklist output and parses the table into a dict
    """
    tasks = check_output(['tasklist']).decode('cp866', 
'ignore').split("\r\n")
    p = []
    for task in tasks:
        m = re.match(b'(.*?)\\s+(\\d+)\\s+(\\w+)\\s+(\\w+)\\s+(.*?)\\s.*', task.encode())
        if m is not None:
            p.append({"image":m.group(1).decode(),
                     "pid":int(m.group(2).decode()),
                    "session_name":m.group(3).decode(),
                    "session_num":int(m.group(4).decode()),
                    "mem_usage":int(m.group(5).decode('ascii', 'ignore'))})
    return p


def test():
    print(*[line.decode('cp866', 'ignore') for line in Popen('tasklist', stdout=PIPE).stdout.readlines()])

    lstp = get_processes_running()
    for p in lstp:
        print(p) …
Run Code Online (Sandbox Code Playgroud)

python python-3.x

0
推荐指数
1
解决办法
4715
查看次数