部署的Python应用程序中出现UnicodeEncode错误

2024-05-06 20:30:08 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个简单的python/pyqt应用程序,它将数据插入到SQLITE数据库表中, 有些条目包含特殊字符,如元音变音。 我使用eclipse进行开发,对其进行了测试,并成功地插入了所有数据,没有出现任何错误。 然后我决定为我的应用程序创建一个可执行文件。我使用py2exe创建可执行文件。我的设置.py如下所示

from distutils.core import setup
import py2exe
import os
includes=["sqlite3","sip","PyQt4", "PyQt4.QtGui"]
excludes=[]
packages=[]
dll_excludes=['libgdk-win32-1.0-0.dll', 'libgobject-2.0-0.dll', 'tcl84.dll', 'tk84.dll']

setup(

      options={"py2exe": {"compressed": 2,
                          "optimize": 2,
                          "includes": includes,
                          "excludes": excludes,
                          "packages": packages,
                          "dll_excludes": dll_excludes,
                          "bundle_files": 2,
                          "dist_dir": "dist",
                          "xref": False,
                          "skip_archive": False,
                          "ascii": False,
                          "custom_boot_script": '',
                          }
               },
      windows=['MainWindow.py'],     
      )

当我在一个“dist”文件夹中得到一个可执行的应用程序时,它似乎可以正常工作,当我插入相同的数据时,它会在特殊字符(元音变音符)处出现。我成功地插入了100个条目中的60个,第一次出现重音字符会导致可执行文件出现错误消息

(, UnicodeEncodeError('ascii', u'Citro\xebnCX', 5, 6, 'ordinal not in range(128)'), )

碰巧我把雪铁龙塞进了桌子里,“e”是法国口音的字符

我不知道为什么当我在eclipse环境中运行python/pyqt应用程序时,没有出现错误,但是一旦我创建了一个可执行文件,就会出现这个错误。在

我应该在安装文件中做什么更改


谢谢。我应用了解决方案 ^{pr2}$

这对我很有效。不是原始解决方案,在SO How to set default encoding in Python (setdefaultencoding() function does not exist)?上看到的


Tags: 数据importfalse应用程序可执行文件packagesdist错误
3条回答

使用Jackson,您可以为JSON编写自己的反序列化程序,并根据需要读取:

public static class Events {
    private final String[] event;
    private final String[][] bid;
    private final String[][] location;

    public Events(String[] event, String[][] bid, String[][] location) {
        this.event = event;
        this.bid = bid;
        this.location = location;
    }

    public String[] getEvent() {
        return event;
    }

    public String[][] getBid() {
        return bid;
    }

    public String[][] getLocation() {
        return location;
    }
}

private class EventsDeserializer extends StdDeserializer<Events> {
    protected EventsDeserializer() {
        super(Events.class);
    }

    @Override
    public Events deserialize(JsonParser p, DeserializationContext ctxt) throws IOException, JsonProcessingException {
        ArrayNode arrayNode = p.readValueAsTree();

        String[] events = new String[arrayNode.size()];
        String[][] bid = new String[arrayNode.size()][0];
        String[][] location = new String[arrayNode.size()][0];

        for (int i = 0; i < arrayNode.size(); i++) {
            JsonNode internalNode = arrayNode.get(i);
            events[i] = internalNode.get("Event").asText();
            bid[i] = convertToArray(internalNode.get("Studios"));
            location[i] = convertToArray(internalNode.get("Location"));
        }

        return new Events(events, bid, location);
    }

    private String[] convertToArray(JsonNode childNode) {
        String[] locations = new String[0];
        if (childNode != null && childNode.isArray()) {
            ArrayNode locationNodeArrayNode = (ArrayNode) childNode;
            locations = new String[locationNodeArrayNode.size()];
            for (int j = 0; j < locations.length; j++) {
                locations[j] = locationNodeArrayNode.get(j).asText();
            }
        }
        return locations;
    }
}

@Test
public void test() throws Exception {
    SimpleModule sm = new SimpleModule();
    sm.addDeserializer(Events.class, new EventsDeserializer());

    ObjectMapper mapper = new ObjectMapper();
    mapper.registerModule(sm);

    Events events = mapper.readValue(JSON, Events.class);
    System.out.println(events);
}

但我建议您使内部结构更接近原始Json:

  public static class Event {
    @JsonProperty("Event")
    private String event;
    @JsonProperty("Studios")
    private List<String> bid;
    @JsonProperty("Location")
    private List<String> location;

    public String getEvent() {
        return event;
    }

    public void setEvent(String event) {
        this.event = event;
    }

    public List<String> getLocation() {
        return location;
    }

    public void setLocation(List<String> location) {
        this.location = location;
    }
}

@Test
public void test() throws Exception {
    ObjectMapper mapper = new ObjectMapper();
    Event[] jsonEvent = mapper.readValue(JSON, Event[].class);
    System.out.println(events);
}

正如您所见,如果您提供正确的映射,Jackson能够为您完成所有工作。它将帮助您获得更清晰的代码,每个节点都有单独的实例,并且不会在一个数组中混合所有对象,这看起来像是糟糕的设计

根据需要尝试此功能

public class Test {

private static final String[]  EventName = new String[50];
private static final String[][] Bid = new String[50][50];
private static final String[][] location= new String[50][50];

public static void main(String[] args) throws ParseException {

        String sampleJSON = "[\n" +
            "  {\n" +
            "    \"Event\": \"Wedding\",\n" +
            "    \"Studios\": [\n" +
            "      \"Studio 1\",\"Studio 2\"\n" +
            "    ],\n" +
            "    \"EventObject\": [\"Ernakulam\",\"Bangalore\"]\n" +
            "  },\n" +
            "  {\n" +
            "    \"Event\": \"Birthday\",\n" +
            "    \"Studios\": [\n" +
            "      \"Studio 1\"\n" +
            "    ],\n" +
            "    \"EventObject\": [\"Ernakulam\"]\n" +
            "\n" +
            "  },\n" +
            "  {\n" +
            "    \"Event\": \"Engagement\",\n" +
            "    \"Studios\": [\n" +
            "       \"Studio 1\",\"Studio 2\",\"Studio 2\"\n" +
            "    ],\n" +
            "    \"EventObject\": [\"Ernakulam\",\"Bangalore\",\"Angamaly\"]\n" +
            "  }\n" +
            "]";


    Gson gson = new Gson();

    ArrayList<EventObject> eventObjectArrayList = gson.fromJson(sampleJSON, new TypeToken<List<EventObject>>(){}.getType());

    for (int i = 0; i < eventObjectArrayList.size(); i++) {

        EventName[i] = eventObjectArrayList.get(i).getEvent();

        for (int j = 0; j < eventObjectArrayList.get(i).getStudios().size(); j++) {
            Bid[i][j] = eventObjectArrayList.get(i).getStudios().get(j);
        }

        for (int k = 0; k < eventObjectArrayList.get(i).getLocation().size(); k++) {
            location[i][k] = eventObjectArrayList.get(i).getLocation().get(k);
        }

    }
}
}

You Need GSON jar com.google.code.gson:gson:2.2.4 import it into your project or add jar as lib in your project.

This is your EventObject class

public class EventObject implements Serializable {

String Event;
ArrayList<String> Studios;
ArrayList<String> Location;

public EventObject() {
}

public String getEvent() {
    return Event;
}

public void setEvent(String event) {
    Event = event;
}

public ArrayList<String> getStudios() {
    return Studios;
}

public void setStudios(ArrayList<String> studios) {
    Studios = studios;
}

public ArrayList<String> getLocation() {
    return Location;
}

public void setLocation(ArrayList<String> location) {
    Location = location;


 }
}

java中有多个json解析库
例如,您可以使用javax。json

那样的话你可以

try(JsonReader jsonReader = Json.createReader(new StringReader(yourJsonString))){
 JsonArray arr = jsonReader.readArray();
 ... run through the entries in arr here and fill your arrays accordingly ...
}

但我应该注意到,您试图创建的结构毫无意义,而且非常不类似java。我建议您创建适当的类来代表活动、场地和投标。它最终会让你的生活更轻松

相关问题 更多 >