gpt4 book ai didi

python - 函数在每次运行时不返回相同的结果

转载 作者:太空宇宙 更新时间:2023-11-04 01:23:25 25 4
gpt4 key购买 nike

我正在尝试用 HTML 实体替换特殊字符,但使用相同的输入结果是随机的,我不明白为什么。

代码如下:

def secure(text):
hsconvert = {"\'": "\\'", "\"": "\\\"", "¢": "&cent;", "©": "&copy;", "÷": "&divide;", ">": "&gt;", "<": "&lt;", "µ": "&micro;", "·": "&middot;", "¶": "&para;", "±": "&plusmn;", "€": "&euro;", "£": "&pound;", "®": "&reg;", "§": "&sect;", "™": "&trade;", "¥": "&yen;", "á": "&aacute;", "Á": "&Aacute;", "à": "&agrave;", "À": "&Agrave;", "â": "&acirc;", "Â": "&Acirc;", "å": "&aring;", "Å": "&Aring;", "ã": "&atilde;", "Ã": "&Atilde;", "ä": "&auml;", "Ä": "&Auml;", "æ": "&aelig;", "Æ": "&AElig;", "ç": "&ccedil;", "Ç": "&Ccedil;", "é": "&eacute;", "É": "&Eacute;", "è": "&egrave;", "È": "&Egrave;", "ê": "&ecirc;", "Ê": "&Ecirc;", "ë": "&euml;", "Ë": "&Euml;", "í": "&iacute;", "Í": "&Iacute;", "ì": "&igrave;", "Ì": "&Igrave;", "î": "&icirc;", "Î": "&Icirc;", "ï": "&iuml;", "Ï": "&Iuml;", "ñ": "&ntilde;", "Ñ": "&Ntilde;", "ó": "&oacute;", "Ó": "&Oacute;", "ò": "&ograve;", "Ò": "&Ograve;", "ô": "&ocirc;", "Ô": "&Ocirc;", "ø": "&oslash;", "Ø": "&Oslash;", "õ": "&otilde;", "Õ": "&Otilde;", "ö": "&ouml;", "Ö": "&Ouml;", "ß": "&szlig;", "ú": "&uacute;", "Ú": "&Uacute;", "ù": "&ugrave;", "Ù": "&Ugrave;", "û": "&ucirc;", "Û": "&Ucirc;", "ü": "&uuml;", "Ü": "&Uuml;", "ÿ": "&yuml;", "\\":"\\\\"};
for i, j in hsconvert.items():
text = text.replace(i, j)
return text

print(secure("La Vie d'Adèle, chapitres 1 & 2"))

控制台输出如下:

>>> ================================ RESTART ================================
>>>
La Vie d\'Ad&egrave;le, chapitres 1 & 2
['TV Movie', 'Video Game', 'TV Episode', 'TV Series', 'TV Series ', 'Short', 'TV Mini-Series']
>>> ================================ RESTART ================================
>>>
La Vie d\\'Ad&egrave;le, chapitres 1 & 2
['TV Movie', 'Video Game', 'TV Episode', 'TV Series', 'TV Series ', 'Short', 'TV Mini-Series']

问题在于 ' 字符,它有时返回为 \',有时返回为 \\'

我认为它来自字典中的最后一项,"\\":"\\\\" 但我不明白为什么每次运行时它的解释都不一样.

最佳答案

正如您在回答中推测的那样,问题是对字典的迭代没有定义的顺序。

来自Python 3 documentation :

Performing list(d.keys()) on a dictionary returns a list of all the keys used in the dictionary, in arbitrary order (if you want it sorted, just use sorted(d.keys()) instead).

虽然没有明确说明,但items()也是一样。

在这种情况下,看到迭代之间的顺序发生变化我有点惊讶,但在这种情况下任意意味着未定义——任何顺序在技术上都是有效的。如果你想要一致的结果,我建议重新设计你的算法,使其对项目的顺序完全不敏感;如果做不到这一点,首先对输出进行排序或使用 OrderedDict 至少可以解决一致性问题。

关于python - 函数在每次运行时不返回相同的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19757214/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com