【问题标题】:Removing a set string from each line while the file is being read在读取文件时从每一行中删除一组字符串
【发布时间】:2016-10-27 17:34:29
【问题描述】:

我有一个 .txt 文件,它通过我无法编辑的 powershell 脚本提取用户列表。创建用户列表后,它会返回:

"Scott Smith","user"
"Tom Smith","user"
"Paul Smith","user"

我试图做一个替换

s = set()

with open('OldUserList.txt') as f:
     for line in f:
        s.add(line)


list2 = open('NewUserList.txt', 'r+')

for ii in list2:
   if ii not in s:
      list2.write(ii.strip("\n")+" ***\n")
      replace('","user"','')

我得到的是:

Traceback (most recent call last):
  File "C:\Python32\readlist.py", line 13, in <module>
    replace('","user"","')
NameError: name 'replace' is not defined

我想知道.replace 应该使用什么?我已经在手册和我在本网站上看到的示例中看到过多次使用它。任何关于这个或更好的写作方式的建议将不胜感激。谢谢。

【问题讨论】:

  • "Scott Smith"'"user" 这是一个错字,应该是"Scott Smith","user"?
  • @MooingRawr 是的,对不起,这是我的错

标签: python string python-3.x replace


【解决方案1】:

方法是string.replace(old, new),所以你的情况是:

for ii in list2:
   if ii not in s:
      list2.write((ii.strip("\n")+" ***\n").replace('","user"', ''))

【讨论】:

  • 这不起作用,因为它将 NewUserList 中的所有用户标记为新用户,即使他们在旧列表中,它们也被标记为好像不是:/
  • 所以你想从字符串中删除 ","user""?
  • 是的,我想我需要在一个单独的函数中执行此操作才能在比较发生之前运行,这样它就不会错误地标记
  • 我更新了上面的代码,试试看能不能解决问题。
  • 这确实删除了字符串,但它将每一行都标记为新用户。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-08-10
  • 2012-03-27
  • 1970-01-01
  • 1970-01-01
  • 2019-11-11
  • 1970-01-01
  • 2013-05-17
相关资源
最近更新 更多