我正在尝试根据句子中的字符数进行一些动态编程。英文字母的哪个字母占据了屏幕上最多的像素?
答案 0 :(得分:660)
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb
cccccccccccccccccccccccccccccccccccccccc
ddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd
eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee
fffffffffffffffffffffffffffffffffffffffffffffffff
gggggggggggggggggggggggggggggggggggggggg
hhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh
iiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiii
jjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjj
kkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkk
llllllllllllllllllllllllllllllllllllllllll
nnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnn
oooooooooooooooooooooooooooooooooooooooo
pppppppppppppppppppppppppppppppppppppppppp
qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq
rrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrr
ssssssssssssssssssssssssssssssssssssssssssss
tttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttиt/ p>
uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu
vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv
wwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwww
xxxxxxxxxxxxxxxxxxxx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VVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV
哇哇哇哇哇哇哇哇哇哇哇哇哇哇哇XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
YYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYY
ZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZ
W胜利。
当然,这是一个愚蠢的实证实验。哪个字母最宽,没有单一的答案。这取决于字体。因此,您必须进行类似的实证实验,以找出适合您环境的答案。但事实是,大多数字体遵循相同的惯例,而资本W将是最广泛的。
答案 1 :(得分:102)
继Ned Batchelder非常实用的答案,因为我来到这里想知道数字:
0000000000000000000000000000000000000000
1111111111111111111111111111111111111111
2222222222222222222222222222222222222222
3333333333333333333333333333333333333333
4444444444444444444444444444444444444444
5555555555555555555555555555555555555555
6666666666666666666666666666666666666666
7777777777777777777777777777777777777777
8888888888888888888888888888888888888888
9999999999999999999999999999999999999999
答案 2 :(得分:17)
程序化解决方案怎么样?
var capsIndex = 65;
var smallIndex = 97
var div = document.createElement('div');
div.style.float = 'left';
document.body.appendChild(div);
var highestWidth = 0;
var elem;
for(var i = capsIndex; i < capsIndex + 26; i++) {
div.innerText = String.fromCharCode(i);
var computedWidth = window.getComputedStyle(div, null).getPropertyValue("width");
if(highestWidth < parseFloat(computedWidth)) {
highestWidth = parseFloat(computedWidth);
elem = String.fromCharCode(i);
}
}
for(var i = smallIndex; i < smallIndex + 26; i++) {
div.innerText = String.fromCharCode(i);
var computedWidth = window.getComputedStyle(div, null).getPropertyValue("width");
if(highestWidth < parseFloat(computedWidth)) {
highestWidth = parseFloat(computedWidth);
elem = String.fromCharCode(i);
}
}
div.innerHTML = '<b>' + elem + '</b>' + ' won';
&#13;
答案 3 :(得分:14)
我相信W
这封信是最广泛的。
答案 4 :(得分:12)
资本“M”通常是最广泛的。
答案 5 :(得分:5)
Chrome中的Arial 30px - W获胜。
答案 6 :(得分:5)
根据您的平台,可能有一种方法是使用width属性以某种方式从字符串或DrawText()函数中“getWidth”。
我会做一个简单的algortime,利用所需的字体,然后运行alfabet并将其存储在一个小配置中,或者只是在初始化时计算它,因为从A到Z的循环不是很难。
答案 7 :(得分:5)
它还取决于字体。我在1年或2年前使用Processing和Helvetica做了这个,并且按照像素增加的顺序是ILJTYFVCPAXUZKHSEDORGNBQMW。我们的想法是在画布上使用您正在查看的字体绘制文本,计算像素,然后使用HashMap或Dictionary进行排序。
当然,这可能与您的使用没有直接关系,因为这会计算像素区域而不仅仅是宽度。也可能有点矫枉过正。
void setup() {
size(30,30);
HashMap hm = new HashMap();
fill(255);
PFont font = loadFont("Helvetica-20.vlw");
textFont(font,20);
textAlign(CENTER);
for (int i=65; i<91; i++) {
background(0);
text(char(i),width/2,height-(textDescent()+textAscent())/2);
loadPixels();
int white=0;
for (int k=0; k<pixels.length; k++) {
white+=red(pixels[k]);
}
hm.put(char(i),white);
}
HashMap sorted = getSortedMap(hm);
String asciiString = new String();
for (Iterator<Map.Entry> i = sorted.entrySet().iterator(); i.hasNext();) {
Map.Entry me = (Map.Entry)i.next();
asciiString += me.getKey();
}
println(asciiString); //the string in ascending pixel order
}
public HashMap getSortedMap(HashMap hmap) {
HashMap map = new LinkedHashMap();
List mapKeys = new ArrayList(hmap.keySet());
List mapValues = new ArrayList(hmap.values());
TreeSet sortedSet = new TreeSet(mapValues);
Object[] sortedArray = sortedSet.toArray();
int size = sortedArray.length;
// a) Ascending sort
for (int i=0; i<size; i++) {
map.put(mapKeys.get(mapValues.indexOf(sortedArray[i])), sortedArray[i]);
}
return map;
}
答案 8 :(得分:3)
计算字体宽度的解决方案有点像xxx发布的解决方案,是由Alex Michael在他的博客上发布的(这有趣地将我链接到这里)。
<强>要点:强>
原帖: http://alexmic.net/letter-pixel-count/
<强>代码:强>
# -*- coding: utf-8 -*-
from __future__ import division
import os
from collections import defaultdict
from math import sqrt
from PIL import Image, ImageDraw, ImageFont
# Make a lowercase + uppercase alphabet.
alphabet = 'abcdefghijklmnopqrstuvwxyz'
alphabet += ''.join(map(str.upper, alphabet))
def draw_letter(letter, font, save=True):
img = Image.new('RGB', (100, 100), 'white')
draw = ImageDraw.Draw(img)
draw.text((0,0), letter, font=font, fill='#000000')
if save:
img.save("imgs/{}.png".format(letter), 'PNG')
return img
def count_black_pixels(img):
pixels = list(img.getdata())
return len(filter(lambda rgb: sum(rgb) == 0, pixels))
def available_fonts():
fontdir = '/Users/alex/Desktop/English'
for root, dirs, filenames in os.walk(fontdir):
for name in filenames:
path = os.path.join(root, name)
try:
yield ImageFont.truetype(path, 100)
except IOError:
pass
def letter_statistics(counts):
for letter, counts in sorted(counts.iteritems()):
n = len(counts)
mean = sum(counts) / n
sd = sqrt(sum((x - mean) ** 2 for x in counts) / n)
yield letter, mean, sd
def main():
counts = defaultdict(list)
for letter in alphabet:
for font in available_fonts():
img = draw_letter(letter, font, save=False)
count = count_black_pixels(img)
counts[letter].append(count)
for letter, mean, sd in letter_statistics(counts):
print u"{0}: {1:.2f} ± {2:.2f}".format(letter, mean, sd)
if __name__ == '__main__':
main()
答案 9 :(得分:1)
这取决于字体。我会用你最熟悉的编程语言创建一个小程序,在那里你将字母表的每个字母画成n倍m大小的位图。用白色初始化每个像素。然后在绘制每个字母后计算白色像素的数量并保存该数字。您找到的最高数字是您正在寻找的数字。
编辑:如果你实际上只对哪一个占用最大的矩形感兴趣(但看起来你真的在那之后,而不是像素),你可以使用各种API调用来查找大小,但是这取决于您的编程语言。例如,在Java中,您将使用FontMetrics类。
答案 10 :(得分:1)
我知道接受的答案是W,W代表WIN。
但是,在这种情况下,W也用于宽度。使用的案例研究使用简单的宽度测试来检查像素,但它只是宽度,而不是总像素数。作为一个简单的反例,接受的答案假设O和Q占用相同数量的像素,但它们只占用相同的空间量。
因此,W占用了最多的空间。但是,这是它破解的所有像素吗?
让我们获得一些经验数据。我从下面的B,M和W创建了imgur图像。然后我分析了它们的像素数(见下文),结果如下:
B:114像素
M:150像素
W:157像素
以下是我如何将它们送入画布并分析图像中的原始像素数据。
var imgs = {
B : "//i.imgur.com/YOuEPOn.png",
M : "//i.imgur.com/Aev3ZKQ.png",
W : "//i.imgur.com/xSUwE7w.png"
};
window.onload = function(){
for(var key in imgs){(function(img,key){
var Out = document.querySelector("#"+key+"Out");
img.crossOrigin = "Anonymous";
img.src=imgs[key];
img.onload = function() {
var canvas = document.querySelector('#'+key);
(canvas.width = img.width,canvas.height = img.height);
var context = canvas.getContext('2d');
context.drawImage(img, 0, 0);
var data = context.getImageData(0, 0, img.width, img.height).data;
Out.innerHTML = "Total Pixels: " + data.length/4 + "<br>";
var pixelObject = {};
for(var i = 0; i < data.length; i += 4){
var rgba = "rgba("+data[i]+","+data[i+1]+","+data[i+2]+","+data[i+3]+")";
pixelObject[rgba] = pixelObject[rgba] ? pixelObject[rgba]+1 : 1;
}
Out.innerHTML += "Total Whitespace: " + pixelObject["rgba(255,255,255,255)"] + "<br>";
Out.innerHTML += "Total Pixels In "+ key +": " + ((data.length/4)-pixelObject["rgba(255,255,255,255)"]) + "<br>";
};
})(new Image(),key)}
};
&#13;
<table>
<tr>
<td>
<canvas id="B" width="100%" height="100%"></canvas>
</td>
<td id="BOut">
</td>
</tr>
<tr>
<td>
<canvas id="M" width="100%" height="100%"></canvas>
</td>
<td id="MOut">
</td>
</tr>
<tr>
<td>
<canvas id="W" width="100%" height="100%"></canvas>
</td>
<td id="WOut">
</td>
</tr>
</table>
&#13;
答案 11 :(得分:1)
想知道真正最长的字形,而不仅仅是猜测吗?
我不仅在谈论字母,数字和通用符号(!,@等)。我的意思是UTF-16的所有32,834个字符中最长的字形。
因此,我从@N K的答案开始,它有一个程序化的解决方案,并对它做了一些轻微修改:
var capsIndex = 65;
var smallIndex = 97;
var div = document.createElement('div');
div.style.float = 'left';
document.body.appendChild(div);
var highestWidth = 0;
var elem;
for(var i = capsIndex; i < 32834; i++) {
div.innerText = String.fromCharCode(i);
var computedWidth = window.getComputedStyle(div, null).getPropertyValue("width");
if(highestWidth < parseFloat(computedWidth)) {
highestWidth = parseFloat(computedWidth);
elem = String.fromCharCode(i);
}
}
div.innerHTML = '<b>' + elem + '</b>' + ' won';
运行此命令并等待(和等待)后,将输出ௌ won
。
在那里,它是UTF-32中最长的字符!
请注意,在某些字体上,最长的字形是﷽,但是其他字体(特别是等宽字体)与字符重叠,就像程序将程序考虑在内的字体一样。
答案 12 :(得分:0)
这取决于字体。例如,交叉零比平常占用的要多得多。
但是,如果有人猜测,我会选择X或B.
答案 13 :(得分:0)
此代码将获取所有字符的宽度作为数组:
const alphabet = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
var widths = [];
var div = document.createElement('div');
div.style.float = 'left';
document.body.appendChild(div);
var highestObservedWidth = 0;
var answer;
for (var i = 0; i < alphabet.length; i++) {
div.innerText = alphabet[i];
var computedWidthString = window.getComputedStyle(div, null).getPropertyValue("width");
var computedWidth = parseFloat(computedWidthString.slice(0, -2));
// console.log(typeof(computedWidth));
widths[i] = computedWidth;
if(highestObservedWidth < computedWidth) {
highestObservedWidth = computedWidth;
answer = div.innerText;
}
}
div.innerHTML = '<b>' + answer + '</b>' + ' won';
// console.log(widths.sort((a, b) => a - b));
答案 14 :(得分:0)
或者,如果您想要一张宽度地图,不仅包含上述的字母(数字)字符(就像我在非浏览器环境中需要的那样)
const chars = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "!", "\"", "#", "$", "%", "'", "(", ")", "*", "+", ",", "-", ".", "/", ":", ";", "=", "?", "@", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "[", "\\", "]", "^", "_", "`", "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "{", "|", "}", "~", " ", "&", ">", "<"]
const test = document.createElement('div')
test.id = "Test"
document.body.appendChild(test)
test.style.fontSize = 12
const result = {}
chars.forEach(char => {
let newStr = ""
for (let i = 0; i < 10; i++) {
if (char === " ") {
newStr += " "
} else {
newStr += char
}
}
test.innerHTML = newStr
const width = (test.clientWidth)
result[char] = width / 10
})
console.log('RESULT:', result)
#Test
{
position: absolute;
/* visibility: hidden; */
height: auto;
width: auto;
white-space: nowrap; /* Thanks to Herb Caudill comment */
}