Tag Archives: python

The reason and solution of the error of join function: sequence item 0: expected STR instance, int found

When I was writing code the other day, the task was to separate the incoming parameters with “_” and then append them to the file
Direct up code

def operate(file_path, *args):
    f = open(file_path, mode="a", encoding="utf-8")
    s = ""
    s = '_'.join(args)
    f.write(s)
    f.flush()
    f.close()
operate("hhhh.txt", 123, 456, 789)

Receive a string, but I wrote a number by mistake, then reported an error
TypeError: sequence item 0: expected STR instance, int found TypeError: sequence item 0: expected STR instance, int found TypeError: sequence item 0: expected STR instance, int found
Then look for the document, and here’s the original text
Return a string which is the concatenation of the strings in iterable. A TypeError will be raised if there are any non-string values in iterable, including bytes objects. The separator between elements is the string providing this method.
The join function is a string function, and the arguments and inserts are strings
So:
S = ‘_’.join(args) to

s = '_'.join(str(args).strip())

That’s it!
 
 
 

Type error: sequence item 0: expected STR instance, int found

TypeError: sequence item 0: expected STR instance, int found TypeError: sequence item 0: expected STR instance, int found
List1 =[1,’two’,’three’,4]
print(‘ ‘.join(list1))
I thought it would print 1, two, three, four
The result was an error
Traceback (most recent call last):
File “< pyshell#27>” , line 1, in < module>
print(” “.join(list1))
peerror: sequence item 0: expected STR instance, int found
p> (“.join(list1))
TypeError: sequence item 0: expected STR instance, int found
A list of numbers cannot be converted directly to a string.
Print (” “.join(‘%s’ %id for id in list1))
That is, iterating through the elements of the list, converting them to strings. So I can print 1, 2, 3, 4.

ValueError: need more than 0 values to unpack

Split () error, valueError: need more than 0 values to unpack

Check the data, it is found that the number of variables on the left and right sides is inconsistent. Carefully check, it is found that there is an empty behavior in the TXT read at the end, so that there is no value after the split at the end, so it cannot be copied to the two variables on the left.

As shown in the figure, delete the last line of space and rerun it.

Therefore, when this error occurs, make sure that the content on both sides is correct.

[solved] error: valueerror: expected 2D array, got scalar array instead

Error code:

new_x = 84610
pre_y = model.predict(new_x)
print(pre_y)

Error result:

ValueError: Expected 2D array, got scalar array instead:
array=84610.
Reshape your data either using array.reshape(-1, 1) if your data has a single feature or array.reshape(1, -1) if it contains a single sample.

Solution:

Reshape data using array
Reshape data using array
Reshape data using array If the data has a single function or array, resize the shape (-1, 1). If the data contains a single example, resize the shape (1, -1).
Solution:
add

new_x = np.array(new_x).reshape(1, -1)

Modified code:

new_x = 84610
new_x = np.array(new_x).reshape(1, -1)
pre_y = model.predict(new_x)
print(pre_y)

Reproduced in: https://www.cnblogs.com/hankleo/p/11310272.html

ValueError: need at least one array to concatenate

keywords
python
Content of the error
ValueError: need at least one array to concatenate
why
Wrong path
Possible places to start
1. Check the path written in the running py file
2. If you are a PyCharm remote connection, it is recommended to check whether “Automatic synchronization to the server” is enabled (open method: Tools — Deployment — Automatic Upload).

Build your own resnet18 network and load torch vision’s own weight

import torch
import torchvision
import cv2 as cv
from utils.utils import letter_box
from model.backbone import ResNet18


model1 = ResNet18(1)
model2 = torchvision.models.resnet18(progress=False)
fc = model2.fc
model2.fc = torch.nn.Linear(512, 1)
# print(model)
model_dict1 = model1.state_dict()
model_dict2 = torch.load('resnet18.pth')
model_list1 = list(model_dict1.keys())
model_list2 = list(model_dict2.keys())
len1 = len(model_list1)
len2 = len(model_list2)
minlen = min(len1, len2)
for n in range(minlen):
    if model_dict1[model_list1[n]].shape != model_dict2[model_list2[n]].shape:
        continue
    model_dict1[model_list1[n]] = model_dict2[model_list2[n]]

model1.load_state_dict(model_dict1)
missing, unspected = model2.load_state_dict(model_dict2)
image = cv.imread('zhn1.jpg')
image = letter_box(image, 224)
image = image[:, :, ::-1].transpose(2, 0, 1)
print('Network loading complete.')
model1.eval()
model2.eval()
with torch.no_grad():
    image = torch.tensor(image/256, dtype=torch.float32).unsqueeze(0)
    predict1 = model1(image)
    predict2 = model2(image)
print('finished')
# torch.save(model.state_dict(), 'resnet18.pth')

ValueError: not enough values to unpack (expected 2, got 0)

ValueError: not enough values to unpack (Expected 2, got 0) sometimes appears when reading TXT files. The reason I found myself is that there are several blank lines at the end of the TXT file. Delete the last blank line and make sure that the last line is the text you want to read. The TXT file looks like nothing if you press Enter at the end, but those empty lines actually have one character, the newline \n, so there can be no empty lines.
 

Just like that the blank line between the cursor and the text actually has a newline character on each line.
Click Backspace to go back to your last line of text. Press the direction key of the keyboard cursor can not get down.

Running Python 3.7 web.py Runtimeerror: generator raised stopiteration exception occurred during test

When I first started learning Python, I found an exception when I ran the web.py home page test code.
The code is as follows:

import web
        
urls = (
    '/(.*)', 'hello'
)
app = web.application(urls, globals())

class hello:        
    def GET(self, name):
        if not name: 
            name = 'World'
        return 'Hello, ' + name + '!'

if __name__ == "__main__":
    app.run()

The exceptions are as follows:

Traceback (most recent call last):
  File "C:\Users\HHHHH\AppData\Local\Programs\Python\Python37-32\lib\site-packages\web\utils.py", line 526, in take
    yield next(seq)
StopIteration

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "D:\workspace\HelloPython\Helloworld.py", line 7, in <module>
    app = web.application(urls, globals())
  File "C:\Users\HHHHH\AppData\Local\Programs\Python\Python37-32\lib\site-packages\web\application.py", line 62, in __init__
    self.init_mapping(mapping)
  File "C:\Users\HHHHH\AppData\Local\Programs\Python\Python37-32\lib\site-packages\web\application.py", line 130, in init_mapping
    self.mapping = list(utils.group(mapping, 2))
  File "C:\Users\HHHHH\AppData\Local\Programs\Python\Python37-32\lib\site-packages\web\utils.py", line 531, in group
    x = list(take(seq, size))
RuntimeError: generator raised StopIteration

 
Follow the exception prompt to find the appropriate code (… Utils.py “, line 531, in group), as follows:

Here, call line 524 take method and modify it as follows according to the information on the official website (note the indentation) :

Restart successfully after modification:


END

Install in Python 3. X web.py

Install web.py in Python 3.x
Recently decided to move from Python 2.7 to work on 3.x.
using the database, still chose before more interested in web. Py
but seemed to have all sorts of problems found when installation.

ImporError: No module named ‘utils’
ModuleNotFoundError: No module named ‘db’

I finally decided to give the dev version a try.

pip install web.py==0.40.dev0

It turns out that the dev version of web.py works perfectly on Python 3.x.
I personally tested Python 3.6
The code is as follows:

import pymysql

pymysql.install_as_MySQLdb()
import web

db = web.database(dbn='mysql', host='db_host', port=3306,
                  user='root', pw='password', db='db_name', charset='utf8')

results = db.query('select * from user where id = 1;')

for user in results:
    print(user.name)
    print(user.id_no)

Hopefully this article will help those of you who are looking for web.py available on Python 3.x.

RuntimeError: log_vml_cpu not implemented for ‘Long’

welcome to my blog
Problem description
Implements Torch. Log (tor.from_numpy (NP.array ([1,2,2]))))t implemented for ‘Long’
why
Long data does not support log operations. Why is a Tensor a Long?Since the numpy array is created without specifying a dtype, int64 is used by default, so when the numpy array is converted to torch.tensor, the data type becomes Long
The solution
Reset torch.log(torch.from_numpy(np.array([1,2,2],np.float)))