简体   繁体   English

如何从 .t​​xt 列表中获取数字并将结果保存在另一个 .txt 中?

[英]How to take numbers from a .txt list and save the result in another .txt?

This script has a formula where at the beginning the numbers x1 and x2 in the code are set, and I need to change the code so that the value x1 is taken from the list pre-prepared text document For example, from a document: 'List.txt'这个脚本有一个公式,在开始时设置了代码中的数字x1x2 ,我需要更改代码,以便从列表预先准备好的文本文档中获取值x1例如,来自文档: '列表.txt'

That is, it turns out I need to enter:也就是说,事实证明我需要输入:

with open ("List.txt '", "r") as f:

into place the value x1 = 6 in the code.将值x1 = 6放入代码中。 But how to systematize it?但是如何系统化呢? Just not very rich in knowledge of Python.只是对Python的知识不是很丰富。

List of numbers:号码列表:

1
4
2
15
6
8
13
3
12
5
10
7
14
9
11

Code: (Powered by Python 2.7)代码:(由 Python 2.7 提供支持)

import sys

a=0
b=7
p=37

x1=6
x2=8

if (len(sys.argv)>1):
    x1=int(sys.argv[1])
if (len(sys.argv)>2):
    x2=int(sys.argv[2])
if (len(sys.argv)>3):
    p=int(sys.argv[3])
if (len(sys.argv)>4):
    a=int(sys.argv[4])
if (len(sys.argv)>5):
    b=int(sys.argv[5])


def modular_sqrt(a, p):
    """ Find a quadratic residue (mod p) of 'a'. p
        must be an odd prime.

        Solve the congruence of the form:
            x^2 = a (mod p)
        And returns x. Note that p - x is also a root.

        0 is returned is no square root exists for
        these a and p.

        The Tonelli-Shanks algorithm is used (except
        for some simple cases in which the solution
        is known from an identity). This algorithm
        runs in polynomial time (unless the
        generalized Riemann hypothesis is false).
    """
    # Simple cases
    #

    if legendre_symbol(a, p) != 1:
        return 0
    elif a == 0:
        return 0
    elif p == 2:
        return p
    elif p % 4 == 3:
        return pow(a, (p + 1) / 4, p)

    # Partition p-1 to s * 2^e for an odd s (i.e.
    # reduce all the powers of 2 from p-1)
    #
    s = p - 1
    e = 0
    while s % 2 == 0:
        s /= 2
        e += 1

    # Find some 'n' with a legendre symbol n|p = -1.
    # Shouldn't take long.
    #
    n = 2
    while legendre_symbol(n, p) != -1:
        n += 1

    x = pow(a, (s + 1) / 2, p)
    b = pow(a, s, p)
    g = pow(n, s, p)
    r = e

    while True:
        t = b
        m = 0
        for m in xrange(r):
            if t == 1:
                break
            t = pow(t, 2, p)

        if m == 0:
            return x

        gs = pow(g, 2 ** (r - m - 1), p)
        g = (gs * gs) % p
        x = (x * gs) % p
        b = (b * g) % p
        r = m


def legendre_symbol(a, p):
    """ Compute the Legendre symbol a|p using
        Euler's criterion. p is a prime, a is
        relatively prime to p (if p divides
        a, then a|p = 0)


        Returns 1 if a has a square root modulo
        p, -1 otherwise.
    """
    ls = pow(a, (p - 1) / 2, p)
    return -1 if ls == p - 1 else ls

def egcd(a, b):
    if a == 0:
        return (b, 0, 1)
    else:
        g, y, x = egcd(b % a, a)
        return (g, x - (b // a) * y, y)

def modinv(a, m):
    g, x, y = egcd(a, m)
    if g != 1:
        print ("x")
    else: 
       return x % m


print "a=",a
print "b=",b
print "p=",p

print "x-point=",x1
print "x-point=",x2


z=(x1**3 + a*x1 +b) % p
y1=modular_sqrt(z, p)

z=(x2**3 + a*x2 +b) % p
y2=modular_sqrt(z, p)

print "\nP1\t(%d,%d)" % (x1,y1)
print "P2\t(%d,%d)" % (x2,y2)



s=((-y2)-y1)* modinv(x2-x1,p) 

x3=(s**2-x2-x1) % p

y3=((s*(x2-x3)+y2)) % p

result =  "Q\t(%d,%d)" % (x3,y3)
f = open('Result01.txt', 'w')
f.write(result)
f.close()

Earlier, I saw scripts where numbers are taken from one text document, perform a function, and the result is saved in another text document.早些时候,我看到了一些脚本,其中从一个文本文档中提取数字,执行一个函数,并将结果保存在另一个文本文档中。

Try using the pandas library to read, process and write your numbers.尝试使用 pandas 库来读取、处理和写入您的数字。

import pandas as pd    # import pandas module and call it pd for short
x2 = 6                 
df = pd.read_csv('input_file.txt')    # read the data from a text file into a dataframe
df['x1 times x2'] = df['x1'] * x2     # create new column in your dataframe with result of your function
df.to_csv('output_file.txt', index=False)    # output result of your calculations (dropping the dataframe index column)

Although you're hard coding the values of x1, x2, in your code, they can be redefined, as you're doing here:尽管您在代码中对 x1、x2 的值进行了硬编码,但它们可以重新定义,就像您在此处所做的那样:

if (len(sys.argv)>1):
    x1=int(sys.argv[1])
if (len(sys.argv)>2):
    x2=int(sys.argv[2])

So if you call your script from command line, like C:\\Users\\test.py x1value x2value you can redefine x1 and x2.因此,如果您从命令行调用脚本,例如C:\\Users\\test.py x1value x2value您可以重新定义 x1 和 x2。 If you really want a text file to contain your x1 and x2, just use the following snippet somewhere at the top如果你真的想要一个文本文件来包含你的 x1 和 x2,只需在顶部的某个地方使用以下代码片段

import json
with open("input.json","r",encoding="utf-8") as stream:
    parsed = json.load(stream)
    x1,x2 = parsed["x1"],parsed["x2"]

Contents of "input.json": “input.json”的内容:

{"x1":1,"x2"=2}

With only python without extra dependencies, your can read List.txt as follow只有 python 没有额外的依赖,你可以阅读 List.txt 如下

with open("List.txt","r") as f:
    arrX1 = list(map(int,f.readlines()))

print (arrX1)

The above reads all the lines in f and converts/maps them to integers.以上读取 f 中的所有行并将它们转换/映射为整数。 The list function then gives you an array you can loop through to generate x2 and write to the Result.txt file. list 函数然后为您提供一个数组,您可以循环遍历以生成 x2 并写入 Result.txt 文件。

The above prints以上印

[1, 4, 2, 15, 6, 8, 13, 5, 3, 10, 7, 14, 9, 11] [1, 4, 2, 15, 6, 8, 13, 5, 3, 10, 7, 14, 9, 11]

So for your code replace all lines from 125 downward with因此,对于您的代码,将 125 向下的所有行替换为

# Read numbers from file and put them in an array
with open("List.txt","r") as f:
    arrX1 = list(map(int,f.readlines()))
f.close()

# Open the result file to write to
f = open('Result01.txt', 'w')

# Now get x1 for each item in the list of numbers from the file
# then do the calculations
# and write the result
for x1 in arrX1:
    z=(x1**3 + a*x1 +b) % p
    y1=modular_sqrt(z, p)

    z=(x2**3 + a*x2 +b) % p
    y2=modular_sqrt(z, p)

    print "\nP1\t(%d,%d)" % (x1,y1)
    print "P2\t(%d,%d)" % (x2,y2)

    s=((-y2)-y1)* modinv(x2-x1,p) 

    x3=(s**2-x2-x1) % p

    y3=((s*(x2-x3)+y2)) % p

    result =  "Q\t(%d,%d)" % (x3,y3)
    f.write(result)

f.close()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM