首页 > 解决方案 > 提取python中连续行之间的差异

问题描述

我需要循环遍历文件的 n 行以及i之间的任何行1,以获得(例如等 ..)n-1的单词之间的区别line(n-1) - line(n)line[i]word[j] - line[i+1]word[j]

输入 :

Hey there !
Hey thre !
What a suprise.
What a uprise.
I don't know what to do.
I don't know wt to do.

输出:

e
s
ha

目标是仅提取两个连续行词之间的缺失字符。

我是 python 新手,所以如果你能指导我编写代码,我将不胜感激。

标签: pythonpython-3.x

解决方案


没有任何库:

def extract_missing_chars(s1, s2):
    if len(s1) < len(s2):
        return extract_missing_chars(s2, s1)
    i = 0
    to_return = []
    for c in s1:
        if s2[i] != c:
            to_return.append(c)
        else:
            i += 1
    return to_return

f = open('testfile')
l1 = f.readline()
while l1:
    l2 = f.readline()
    print(''.join(extract_missing_chars(l1, l2)))
    l1 = f.readline()

推荐阅读