Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/325.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
python:ValueError:基数为10的int()的文本无效:“”_Python_File - Fatal编程技术网

python:ValueError:基数为10的int()的文本无效:“”

python:ValueError:基数为10的int()的文本无效:“”,python,file,Python,File,我有一个文本文件,其中包含如下条目 70154::308933::3 UserId::ProductId::Score 我写这个程序的目的是: 对不起,这里的索引有点混乱 def generateSyntheticData(fileName): dataDict = {} # rowDict = [] innerDict = {} try: # for key in range(5): # count = 0 myFile = open(fileName)

我有一个文本文件,其中包含如下条目

70154::308933::3
UserId::ProductId::Score
我写这个程序的目的是: 对不起,这里的索引有点混乱

def generateSyntheticData(fileName):
 dataDict = {}
 # rowDict = []
 innerDict = {}


 try:
    # for key in range(5):
    # count = 0
    myFile = open(fileName)
    c = 0
        #del innerDict[0:len(innerDict)]

    for line in myFile:
        c += 1
        #line = str(line)
        n = len(line)
        #print 'n: ',n
        if n is not 1:
       # if c%100 ==0: print "%d: "%c, " entries read so far"
       # words = line.replace(' ','_')
            words = line.replace('::',' ')

            words = words.strip().split()


            #print 'userid: ', words[0]
            userId = int( words[0]) # i get error here
            movieId = int (words[1])
            rating =float( words[2])
            print "userId: ", userId, " productId: ", movieId," :rating: ", rating
            #print words
            #words = words.replace('_', ' ')
            innerDict = dataDict.setdefault(userId,{})
            innerDict[movieId] = rating
            dataDict[userId] = (innerDict)
            innerDict = {}
except IOError as (errno,strerror):
    print "I/O error({0}) :{1} ".format(errno,strerror)

finally:
    myFile.close() 
print "total ratings read from file",fileName," :%d " %c
return dataDict
但我得到了一个错误:

ValueError: invalid literal for int() with base 10: ''
有趣的是,从另一个文件读取相同格式的数据时,它工作得很好。。 事实上,在发布这个问题时,我注意到了一些奇怪的事情。。 条目70154::308933::3 每个数字都有一个空格。中间有7个空格0个空格1个空格5个空格4个空格::空格3。。。 但是文本文件看起来很好..:仅在复制粘贴时,它显示了这种性质。。 无论如何。。但任何线索都知道发生了什么。
谢谢调试101:只需更改行:

words = words.strip().split()
致:

看看结果如何

我将提到几件事。如果您有文本用户ID::。。。在文件中,如果您尝试处理它,那么尝试将其转换为整数是不可取的

还有。。。异常线路:

if n is not 1:
我可能会这样写:

if n != 1:
如您在评论中所述,如果您最终看到:

['\x007\x000\x001\x005\x004\x00', '\x003\x000\x008\x009\x003\x003\x00', '3']
然后我会检查你的输入文件中的二进制非文本数据。如果您只是在阅读文本并进行修剪/拆分,则永远不应该以二进制信息结束


因为您声明数字之间似乎有空格,所以您应该对文件进行十六进制转储,以找出其中真正的内容。例如,它可能是UTF-16 Unicode字符串。

调试101:只需更改行:

words = words.strip().split()
致:

看看结果如何

我将提到几件事。如果您有文本用户ID::。。。在文件中,如果您尝试处理它,那么尝试将其转换为整数是不可取的

还有。。。异常线路:

if n is not 1:
我可能会这样写:

if n != 1:
如您在评论中所述,如果您最终看到:

['\x007\x000\x001\x005\x004\x00', '\x003\x000\x008\x009\x003\x003\x00', '3']
然后我会检查你的输入文件中的二进制非文本数据。如果您只是在阅读文本并进行修剪/拆分,则永远不应该以二进制信息结束


因为您声明数字之间似乎有空格,所以您应该对文件进行十六进制转储,以找出其中真正的内容。例如,它可能是UTF-16 Unicode字符串。

您看到的空格似乎是NULs\x00。您的文件有99.9%的可能是用UTF-16、UTF-16LE或UTF-16BE编码的。如果这是一个一次性文件,只需用记事本打开它并另存为ANSI,而不是Unicode和Unicode bigendian。但是,如果您需要按原样处理,则需要知道/检测编码是什么。要找出哪个,请执行以下操作:

print repr(open("yourfile.txt", "rb").read(20))
并将输出的srtart与以下内容进行比较:

>>> ucode = u"70154:"
>>> for sfx in ["", "LE", "BE"]:
...     enc = "UTF-16" + sfx
...     print enc, repr(ucode.encode(enc))
...
UTF-16 '\xff\xfe7\x000\x001\x005\x004\x00:\x00'
UTF-16LE '7\x000\x001\x005\x004\x00:\x00'
UTF-16BE '\x007\x000\x001\x005\x004\x00:'
>>>
您可以通过检查前2个字节来制作一个足够好的检测器:

[pseudocode]
if f2b in `"\xff\xfe\xff"`: UTF-16
elif f2b[1] == `"\x00"`: UTF-16LE
elif f2b[0] == `"\x00"`: UTF-16BE
else: cp1252 or UTF-8 or whatever else is prevalent in your neck of the woods.
您可以避免硬编码回退编码:

>>> import locale
>>> locale.getpreferredencoding()
'cp1252'
您的行读取代码如下所示:

rawbytes = open(myFile, "rb").read()
enc = detect_encoding(rawbytes[:2])
for line in rawbytes.decode(enc).splitlines():
    # whatever

哦,行将是unicode对象。。。如果这给了你一个问题,问另一个问题。

你看到的空格似乎是NULs\x00。您的文件有99.9%的可能是用UTF-16、UTF-16LE或UTF-16BE编码的。如果这是一个一次性文件,只需用记事本打开它并另存为ANSI,而不是Unicode和Unicode bigendian。但是,如果您需要按原样处理,则需要知道/检测编码是什么。要找出哪个,请执行以下操作:

print repr(open("yourfile.txt", "rb").read(20))
并将输出的srtart与以下内容进行比较:

>>> ucode = u"70154:"
>>> for sfx in ["", "LE", "BE"]:
...     enc = "UTF-16" + sfx
...     print enc, repr(ucode.encode(enc))
...
UTF-16 '\xff\xfe7\x000\x001\x005\x004\x00:\x00'
UTF-16LE '7\x000\x001\x005\x004\x00:\x00'
UTF-16BE '\x007\x000\x001\x005\x004\x00:'
>>>
您可以通过检查前2个字节来制作一个足够好的检测器:

[pseudocode]
if f2b in `"\xff\xfe\xff"`: UTF-16
elif f2b[1] == `"\x00"`: UTF-16LE
elif f2b[0] == `"\x00"`: UTF-16BE
else: cp1252 or UTF-8 or whatever else is prevalent in your neck of the woods.
您可以避免硬编码回退编码:

>>> import locale
>>> locale.getpreferredencoding()
'cp1252'
您的行读取代码如下所示:

rawbytes = open(myFile, "rb").read()
enc = detect_encoding(rawbytes[:2])
for line in rawbytes.decode(enc).splitlines():
    # whatever

哦,行将是unicode对象。。。如果这给了您一个问题,请问另一个问题。

您如何阅读文本文件?发布你的代码。你是如何读取文本文件的?发布您的代码。我得到以下输出['\x007\x000\x001\x005\x004\x00','\x003\x000\x008\x009\x003\x003\x00','3'],实际上正如您所看到的,这是一个嵌套的dict。。所以我怀疑它给了我钥匙的地址?@Fraz,如果这一行是从一个文本文件中来的,就像你所说的,你永远不应该以文字结束。它应该是文本的。你需要检查你的输入文件。@Fraz我同意paxdiablo,问题可能是你输入数据的编码@帕克斯-关于使用,你是对的!=但是它不会在CPython上工作,因为0-255都是实习的,所以所有的1都有相同的标识。我得到以下输出['\x007\x000\x001\x005\x004\x00','\x003\x000\x008\x009\x003\x003\x00','3'],实际上正如您所看到的,这是一个嵌套的dict。。所以我怀疑它给了我钥匙的地址?@Fraz,如果这一行是从一个文本文件中来的,就像你所说的,你永远不应该以文字结束。它应该是文本的。你需要检查你的输入文件。@Fraz我同意paxdiablo,问题可能是你输入数据的编码@帕克斯-关于使用,你是对的!=但是is不会在CPython上工作,因为0-255是实习的,所以所有1都有相同的身份。@Fraz:很高兴我能帮忙;哪一部分有帮助-便条
广告技巧还是Python代码?嗯。。实际上我只是想让它工作起来。。因此,我们做了一些类似words=words.replace'\x00':我找不到这个函数detect_encoding,它在哪里?@Fraz:很高兴我能帮上忙;哪一部分有用-记事本技巧还是Python代码?嗯。。实际上我只是想让它工作起来。。因此,我们做了一些类似words=words.replace'\x00':我找不到这个函数detect\u encoding,它在哪里?