Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/287.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python链接2个字符串_Python - Fatal编程技术网

Python链接2个字符串

Python链接2个字符串,python,Python,我正在开发python程序,目标是创建一个工具,从文件中提取第一个单词,并将其放在另一个文件的另一行旁边 这是代码片段: lines = open("x.txt", "r").readlines() lines2 = open("c.txt", "r").readlines() for line in lines: r = line.split() line1 = str(r[0]) for line2 in lines2: l2 = line2

我正在开发python程序,目标是创建一个工具,从文件中提取第一个单词,并将其放在另一个文件的另一行旁边

这是代码片段:

lines = open("x.txt", "r").readlines()
lines2 = open("c.txt", "r").readlines()
for line in lines:
    r = line.split()
    line1 = str(r[0])
    for line2 in lines2:
        l2 = line2
    rn = open("b.txt", "r").read()
    os = open("b.txt", "w").write(rn + line1+ "\t" + l2)
但它不能正常工作

我的问题是,我想让这个工具从一个文件中获取第一个单词,并将它放在另一个文件中的一行旁边,以显示文件中的所有行

greetings = open("x.txt", "r").readlines()
names = open("c.txt", "r").readlines()

with open("b.txt", "w") as output_file:
    for greeting, name in zip(greetings, names):
        greeting = greeting.split(" ")[0]
        output = "{0} {1}\n".format(greeting, name)
        output_file.write(output)
例如:

文件:1.txt:

hello there
hi there
文件:2.txt:

michal smith
takawa sama
我希望结果是:

输出:

hello michal smith
hi takaua sama

通过使用zip函数,可以同时循环这两个函数。然后,您可以从问候语中提取第一个单词,并将其添加到名称中以写入文件

greetings = open("x.txt", "r").readlines()
names = open("c.txt", "r").readlines()

with open("b.txt", "w") as output_file:
    for greeting, name in zip(greetings, names):
        greeting = greeting.split(" ")[0]
        output = "{0} {1}\n".format(greeting, name)
        output_file.write(output)

是的,就像Tigerhawk指出的那样,您希望使用
zip
函数,该函数将来自不同iterables的元素组合在同一索引中,以创建元组列表(每个第i个元组都有来自每个列表第i个索引的元素)

示例代码-

lines = open("x.txt", "r").readlines()
lines2 = open("c.txt", "r").readlines()
newlines = ["{} {}".format(x.split()[0] , y) for x, y in zip(lines,lines2)]
with open("b.txt", "w") as opfile:
    opfile.write(newlines)

此代码将在不将文件加载到内存的情况下工作。

嵌套循环不是这样工作的。您正在寻找:
对于zip中的a,b(行,行2):
。当我将它们链接在一起时,阿拉伯语文本已经变成了中文文本,为什么?这听起来像是unicode问题,而不是zip问题。