【问题标题】:Measuring string width in Python在 Python 中测量字符串宽度
【发布时间】:2017-09-10 20:24:04
【问题描述】:

我有一些字体(Times New Roman,14),我需要测量字符串宽度。我从 API 中找到了 matplotlib 和示例:

from matplotlib import rcParams
import os.path
afm_filename = os.path.join(rcParams['datapath'], 'fonts', 'afm', 
               'ptmr8a.afm')
from matplotlib.afm import AFM
afm = AFM(open(afm_filename))
afm.string_width_height('What the heck?')

但我不明白应该粘贴什么而不是“datapaths”、“fonts”、“afm”。 这是在Python中获得刺痛宽度的方法吗?也许另一种方式?

【问题讨论】:

  • 字符串宽度?你的意思是字符串的长度?
  • 问题是,你的文件在哪里?
  • 你的意思是以像素为单位的字符串长度吗?
  • 我的问题是在 Word 中组织一些文本。所以,我使用 python-docx 来阅读 docx 文档。我需要在文档中测量以厘米为单位的字符串宽度。如果我使用默认设置(在上面的代码中):
  • Error: if not line.startswith(b'StartFontMetrics'): TypeError: startswith first arg must be str or a tuple of str, not bytes

标签: python string width


【解决方案1】:
import tkinter as Tkinter 
from tkinter import font as tkFont

Tkinter.Frame().destroy()
txt = tkFont.Font(family="Times New Roman", size=14)
width = txt.measure("What the heck?")
print(width)

【讨论】:

  • 一些错误:文件“E:/=ПРОЕКТЫ=/=PYTHON=/=ТЕКСТ=/Calc_String_Variants/Calc.py”,第 4 行,在 txt = tkFont.Font(family= "Times New Roman", size=14) 文件 "C:\Users\User\AppData\Local\Programs\Python\Python36-32\lib\tkinter\font.py",第 93 行,在 init tk.call("font", "create", self.name, *font) AttributeError: 'NoneType' object has no attribute 'call'
  • 这是一些补充:
  • 再次更新。应该适用于 python 2 和 3。你是什么意思“这是一些添加”?
  • 我在 Python 3 版本中添加了字符串“tkinter.Frame().destroy()”,它可以工作,但它有问题:我的 Word 文档的宽度是 505 毫米。因此,如果我为完整字符串添加所有字母“a”(230 个字母) - 答案是 1840,但是如果我为完整字符串添加所有字母“c”(230 个字母) - 答案是 2070。这是很大的不同,但是在 Word 中是差不多的。
  • 用 destroy() 更新
猜你喜欢
  • 1970-01-01
  • 2021-11-10
  • 2010-11-28
  • 2016-11-04
  • 2018-07-21
  • 2020-04-22
  • 1970-01-01
  • 2019-01-14
  • 2012-04-15
相关资源
最近更新 更多