ord功能不起作用

时间:2016-02-06 18:42:08

标签: python-3.x chr ord

protected function processFilePowerpoint(array $file, array &$files) {
    /** @var \Drupal\wincachedrupal\NetPhp */
    $netphp = \Drupal::service('netphp');

    $runtime = $netphp->getRuntime();

    $runtime->RegisterAssemblyFromFile("libraries/_bin/aspose/Aspose.Slides.dll", "Aspose.Slides");
    $runtime->RegisterAssemblyFromFullQualifiedName("System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", "System.Drawing");

    $destination = strtr(PresentacionSlide::UPLOAD_LOCATION, ['[envivo_presentacion:id]' => $this->entity->id()]);
    file_prepare_directory($destination, FILE_CREATE_DIRECTORY | FILE_MODIFY_PERMISSIONS);

    $sourcefile = drupal_realpath($file['tmppath']);

    $presentation = $runtime->TypeFromName("Aspose.Slides.Presentation")->Instantiate($sourcefile);
    $format = $runtime->TypeFromName("System.Drawing.Imaging.ImageFormat")->Png;

    $x = 0;

    /** @var \NetPhp\Core\NetProxyCollection */
    $slides = $presentation->Slides->AsIterator();

    foreach ($slides as $slide) {
      $x++;
      $bitmap = $slide->GetThumbnail(1, 1);
      $destinationfile = $destination . "\\slide_{$x}.png";
      $bitmap->Save(drupal_realpath($destinationfile), $format);
      $files[] = PresentacionSlide::fromFile($destinationfile);
    }

    $presentation->Dispose();
  }

列表'contents'中的所有内容都应该转换为等效的ascii代码。然而,当'file_ascii2'被转回正常字母时,其中一些已经是正常的字母,甚至认为它已经被添加和减去。 当代码与

一起运行时
file_ascii = [(ord(c)) for c in contents]
f_file = []
for x in range (0, len(file_ascii)): 
    if file_ascii[x] != 32:
        file_ascii2 = (file_ascii[x])
        file_ascii2 = (offset) + (file_ascii2)
        if file_ascii2 > 126:
            file_ascii2 = (file_ascii2) - 94
    print (file_ascii2)
    file_ascii2 = [(chr(i)) for i in file_ascii2]
    f_file.append(file_ascii2)

作为评论,'file_ascii2'被证明是全部整数

1 个答案:

答案 0 :(得分:1)

您从未更改file_ascii列表中的元素。您只更改了变量file_ascii2。您需要返回列表以便在那里反映更改:

if file_ascii[x] != 32:
    file_ascii2 = (file_ascii[x])
    file_ascii2 = (offset) + (file_ascii2)
    if file_ascii2 > 126:
        file_ascii2 = (file_ascii2) - 94
    file_ascii[x] = file_ascii2

或直接将该号码的chr()结果直接附加到f_file列表。

你应该为你的变量使用更好的名字; file_ascii是一个代表字符的数字列表,file_ascii2一个这样的数字,因此您尝试在该数字上使用for循环的列表理解将失败。

在不改变技术的情况下稍微清理代码会导致:

file_ascii = [ord(c) for c in contents]
f_file = []
for index in range(0, len(file_ascii)): 
    codepoint = file_ascii[index]
    if codepoint != 32:
        codepoint += offset
        if codepoint > 126:
            codepoint -= 94
    f_file.append(chr(codepoint))

更容易循环遍历contents并将每个字符转换为循环中的整数:

f_file = []
for character in contents:
    codepoint = ord(character)
    if codepoint != 32:
        codepoint += offset
        if codepoint > 126:
            codepoint -= 94
    f_file.append(chr(codepoint))