Python 如何计算一个文件中多个数字的汉明权重?

Python 如何计算一个文件中多个数字的汉明权重?,python,Python,我有一个文件,每行包含一组数字,如下所示: [222 9 217 21 65 197] [222 9 217 21 65 197] [222 207 217 21 65 197] [ 9 222 217 21 65 197] [222 117 21 65 217 197] [222 117 21 65 217 197] [222 117 21 65 217 197] [222 117 21 65 217 197] ........ 我想计算每个数字的汉

我有一个文件,每行包含一组数字,如下所示:

[222   9 217  21  65 197]
[222   9 217  21  65 197]
[222 207 217  21  65 197]
[  9 222 217  21  65 197]
[222 117  21  65 217 197]
[222 117  21  65 217 197]
[222 117  21  65 217 197]
[222 117  21  65 217 197]
........
我想计算每个数字的汉明权重,结果是:

[6   2 5  3  2 4]
[6   2 5  3  2 4]
[6   6 5  3  2 4]
[2   6 5  3  2 4]
[6   5 3  2  5 4]
[6   5 3  2  5 4]
[6   5  3  2 5 4]
[6   5  3  2 5 3]
........
我使用此脚本计算汉明权重:

hw = [bin(x).count("1") for x in range(256)]
print(hw[207])
但是我只能用一个数字,怎么能用所有的文件呢

能帮我吗

您可以尝试以下方法:

from io import StringIO

text = '''[222   9 217  21  65 197]
[222   9 217  21  65 197]
[222 207 217  21  65 197]
[  9 222 217  21  65 197]
[222 117  21  65 217 197]
[222 117  21  65 217 197]
[222 117  21  65 217 197]
[222 117  21  65 217 197]'''


def hw(number):
    ret = 0
    while number != 0:
        ret += number & 1
        number >>= 1
    return ret
    # might be faster:
    # return bin(number).count('1')

# with open(..., 'r') as file
with StringIO(text) as file:
    for line in file:
        line = line.strip()
        line = line.replace('[', '')
        line = line.replace(']', '')
        numbers = [int(n) for n in line.split()]
        hws = [hw(n) for n in numbers]
        print(hws)
要使其适用于您,请删除上面的
文本
部分,删除
以StringIO(text)作为文件:
行,并将其替换为
以open(…,'r')作为文件
行。您必须在那里插入文件名(或者更好:插入文件的完整路径)


我还提供了不同版本的汉明重量;基于位运算。

用于循环,不需要列表理解

def hamAll(seq):
  output = []
  for i in seq:
    output.append(bin(i).count("1"))
  return output
外壳:

然后,如果你想输入一个文件,我会使用
re
模块

import re

def hamAll(seq):
  output = []
  for i in seq:
    output.append(bin(i).count("1"))
  return output

with open("filename.txt", 'r') as file:
  inputf = file.read()

inputf = re.sub(r"[\n\[\]]", " ", inputf)
numbers = inputf.split(" ")
hamReady = []
for i in numbers:
  if i == "":
    continue
  if i.isdecimal():
    hamReady.append(int(i))

print(hamAll(hamReady))
外壳:


我选择使用在这个答案中找到的计算汉明重量的方法:

使用for循环和一些字符串格式组合,从输入文件中提取文本,提取数字,计算汉明权重,重新格式化数字,然后打印这些数字并将其写入输出文件

示例代码:

def get_hm(x):
    return bin(x).count("1")

def format_numbers(results):
    count = 0
    result = "["
    for x in results:
        if x >= 100:
            result = result + str(x)
        elif x >= 10:
            result = result + " " + str(x)
        else:
            result = result + "  " + str(x)
        if count < len(results):
            result = result + " "
        count += 1
    result = result + "]"
    return result

def get_numbers(line):
    line = line.replace("[", "").replace("]","").replace("\n","")
    results = []
    for x in line.split(" "):
        if x != "" and x != " ":
            results.append(get_hm((int(x))))
    return format_numbers(results)


f = open("input.txt")
y = f.readlines()
for line in y:
    print get_numbers(line)
f.close()

#optional code that writes the results to a file.
f = open("output.txt", "w")
for line in y:
    f.write(get_numbers(line) + "\n")
f.close()
def get_hm(x):
回收箱(x)计数(“1”)
def格式_编号(结果):
计数=0
结果=“[”
对于结果中的x:
如果x>=100:
结果=结果+str(x)
elif x>=10:
结果=结果+“”+str(x)
其他:
结果=结果+“”+str(x)
如果计数
您可以在列表理解中使用嵌套for循环也可以使用正则表达式来提取数字,而不是所有
line
操作:
numbers=[int(n)for n in re.findall('\d+',line)]
或直接获取
hws
作为
hws=[hw(int(n))for n in re.findall('\d+',line)]
======== Restart: test.py ========
[6, 2, 5, 3, 2, 4, 6, 2, 5, 3, 2, 4, 6, 6, 5, 3, 2, 4, 2, 6, 5, 3, 2, 4, 6, 5, 3, 2, 5, 4, 6, 5, 3, 2, 5, 4, 6, 5, 3, 2, 5, 4, 6, 5, 3, 2, 5, 4]
>>>
def get_hm(x):
    return bin(x).count("1")

def format_numbers(results):
    count = 0
    result = "["
    for x in results:
        if x >= 100:
            result = result + str(x)
        elif x >= 10:
            result = result + " " + str(x)
        else:
            result = result + "  " + str(x)
        if count < len(results):
            result = result + " "
        count += 1
    result = result + "]"
    return result

def get_numbers(line):
    line = line.replace("[", "").replace("]","").replace("\n","")
    results = []
    for x in line.split(" "):
        if x != "" and x != " ":
            results.append(get_hm((int(x))))
    return format_numbers(results)


f = open("input.txt")
y = f.readlines()
for line in y:
    print get_numbers(line)
f.close()

#optional code that writes the results to a file.
f = open("output.txt", "w")
for line in y:
    f.write(get_numbers(line) + "\n")
f.close()