【发布时间】:2020-06-09 11:35:11
【问题描述】:
我想在一个文件中选择 n 对单词位置(唯一)并交换它们。我的代码如下,但它从来没有给我我正在寻找的 n 对。
我的逻辑是首先采样 2*n 个元素并创建 n 对。然后遍历文件内容(存储在列表中)并找到正确的位置并进行交换。它不工作。我很难理解它失败的地方。
with open(rname) as rd:
lines = rd.readlines()
for i in range(len(lines)):
lines[i] = lines[i].strip()
sz = sum(len(x.split()) for x in lines)
chosen = random.sample(range(sz),6000)
result = pairwise(chosen)
for (a,b) in result:
flag1 = 0
flag2 = 0
l = 0
ind1 = 0
m = 0
ind2 = 0
j = 0
for y in range(len(lines)):
if ( (j+len(lines[y].split()) >= a) and (flag1 == 0)):
l = y
ind1 = a - j-1
flag1 = 1
if ( (j+len(lines[y].split()) >= b) and (flag2 == 0)):
m = y
ind2 = b - j-1
flag2 = 1
if ( (flag1 == 1) and (flag2 == 1)):
words1 = lines[l].split()
words2 = lines[m].split()
words1[ind1], words2[ind2] = 'swapped'+words2[ind2], 'swapped'+words1[ind1]
lines[l] = ' '.join(words1)
lines[m] = ' '.join(words2)
break
j += len(lines[y].split())
name ='n_file.txt'
with open(wname,'w') as wd:
for line in lines:
print(line, file=wd)
def pairwise(iterable):
a, b = tee(iterable)
next(b, None)
return zip(a, b)
例如,考虑一个包含内容的文件
i am here, where are you
it is none of your business
假设我选择 2 个位置 (2,8)(位置是根据文件中的单词位置定义的,文件中的第一个单词从 0 开始)。我的输出看起来像
i am swappednone where are you
it is swappedhere, of your business
【问题讨论】:
-
请发布文件内容的示例以及正确的输出可能是什么样的。
-
@alaniwi 包括一个例子。
-
因此在您的示例中,您希望在交换单词时保留标点符号。
-
@alaniwi。这是一个错字。对不起。纠正它。单词仅由空格定义。
-
如果你将主要部分抽象成它自己的函数,你的代码会更简洁。一个,给定一个列表和一个整数
n,交换该列表中随机选择的n对。这是问题的核心,不应与执行诸如从文件读取和拆分字符串之类的代码混淆。
标签: python-3.x list file random