当我在python操作器中读取表单文件时 == 总是返回 false



我有一个文件,我尝试从中逐行读取,如果profile picture我每行的 16 个字符,请做某事。 但运算符总是返回 false。

f = open("filename.txt", "r")
count = 0
f.readline()
while True:
chunk = f.readline()
mystr = chunk[-16:]
aa= "profile picture";
if mystr == aa:  ----------------------------->this line always return false 
name.append("@"+f.readline())
count += 1
else:
# print(mystr +"n"+"profile picture" +"n"+mystr=="profile picture")
print(mystr is ' profile picture')
if chunk=='':
break

我的文件是这样的:

m.m_deading profile picture
Ali
m.m_deading's profile picture
m.test
Ali
m.m_deading's profile picture
Ali
m.m_deading's profile picture
m.test
Ali
m.m_deading's profile picture
m.m_deadafafsing
Ali

即使我已经尝试过is但仍然返回错误

个人资料图片字符串末尾有空格。 你可以使用 .strip(( 来摆脱它。 由于您发布的代码中未定义name因此我将其注释掉。

运行后,您可以print(count)确认它找到了其中的 4 个。

f = open("filename.txt", "r")
count = 0
f.readline()
while True:
chunk = f.readline()
mystr = chunk[-16:]
if mystr.strip() == 'profile picture': 
#         name.append("@"+f.readline())
count += 1
else:
pass
if chunk=='':

如果您尝试打印chunk[-16:]的输出,您将看到问题所在。那个卡盘里有一个空格字符。

>>> chunk = "m.m_deading's profile picture"
>>> chunk[-16:]
' profile picture'

但是,如果文件的某些行也包含尾随空格,则可能存在不同类型的问题。如果行中有 2 个尾随空格,会发生什么情况。

>>> chunk = "m.m_deading's profile picture  "
>>> chunk[-16:]
'rofile picture  '

因此,在 2 种情况下,您的程序可能会由于尾随和前导空间问题而失败。所以我的建议是确保文件中没有尾随空格。你可以通过以下方式做到这一点,

chunk = f.readline().strip()

如果打印chunk的值,则现在将看不到尾随空格或前导空格。然后,您可以提取profile picture部分。

mystr = chunk[-15:]

如果你得到16字符,你也会得到一个空格字符。但是现在您只能从生产线中获得profile picture部分。
所以最终的代码是这样的。

f = open("filename.txt", "r")
count = 0
f.readline()
while True:
chunk = f.readline().strip()
mystr = chunk[-15:]

# You can remove the redundant `aa` variable that was here
if mystr == "profile picture":
name.append("@"+f.readline())
count += 1
else:
# print(mystr +"n"+"profile picture" +"n"+mystr=="profile picture")
print(mystr is ' profile picture')
if chunk=='':
break

还有其他一些方法可以处理它。

chunk = f.readline()

if "profile picture" in chunk:
...

此方法将检查您从文件中读取的行中是否存在字符串profile picture。但是,如果profile picture也处于行的中间,这将返回true

chunk = f.readline().strip()

if chunk.endswith("profile picture"):
...

这样,它将检查该行是否以字符串profile picture结尾。因此,您必须确保没有尾随空格。

最新更新