有人可以帮忙吗? 我有这样一个文件:
file = """he is a good man
she is a beautiful woman
this is a clever student
he is a bad neighbour"""
我想在文件中标记形容词,所以我在列表中提取它们,我想用另一种格式替换原始文件,如括号之间。所以列表形容词看起来像这样
ad = "good, bad, clever, beautiful,"
我试过这个
for line in file.splitlines():
for a in ad.split(','):
if a in line:
newline = line.replace(s, '[' + s + ']')
result = file.replace(line, newline)
print result
这给了我这个重复的结果:
he is a [good] man
she is a beatiful woman
this is a clever student
he is a bad neighbor
he is a good man
she is a[ beatiful] woman
this is a clever student
he is a bad neighbor
he is a good man
she is a beatiful woman
this is a[ clever] student
he is a bad neighbor
he is a good man
she is a beatiful woman
this is a clever student
he is a[ bad] neighbor
虽然我期待这样的结果
he is a [good] man
she is a [beautiful] woman
this is a [clever] student
he is a [bad] neighbour
答案 0 :(得分:0)
问题在于你的循环。你没有很好地分割你的形容词,如果你打算使用替换,则不需要分割线。所以,你的代码应该如下:
adj = [word.strip() for word in ad.split(",") if word != ""]
for a in adj:
if a in file:
file = file.replace(a, '[' + a + ']')
print file