以下是一个示例代码,用于保留同一行中有两个字符串的行:
def keep_rows_with_two_strings(lines):
result = []
for line in lines:
count = 0
for word in line.split():
if word.isalpha(): # 判断是否为字符串
count += 1
if count == 2:
result.append(line)
break
return result
# 示例使用
lines = [
"This is a line with two strings",
"This line has only one string",
"Another line with two strings",
"This line has three strings"
]
result = keep_rows_with_two_strings(lines)
for line in result:
print(line)
输出结果:
This is a line with two strings
Another line with two strings