python - 在 .txt 文档中写单词而不重复
问题描述
所以我试图在网站中挑选单词并将它们写.txt
在 python 的文档中。每次出现新单词时我都需要这样做,但这不是问题。问题是每次我运行代码时都会.txt
重复相同的单词。
这是我的代码:
from selenium import webdriver
import time
options = webdriver.ChromeOptions()
options.add_argument('--profile-directory=Default')
options.add_argument('--user-data-dir=D:/Users/daichi/Desktop/Bot/chrome')
url = 'https://web.whatsapp.com/'
driver = webdriver.Chrome('/Users/daichi/Desktop/Bot/chromedriver/chromedriver', options = options)
words = open("words.txt","r+")
driver.get(url)
time.sleep(10)
user = driver.find_element_by_xpath('//span[@title="A"]')
user.click()
time.sleep(2)
messages = driver.find_elements_by_xpath('//*[text()[contains(.,"!web")]]')
for message in messages:
if message.text in words.read():
print("this word is alrealy on the .txt!")
elif message.text not in words.read():
words.write(message.text + "\n")
对不起,我的英语不好,来自巴西的你好。
解决方案
你总是在读同一个文件。
twetts = ['new 1','new 2','new 2']
for twett in twetts:
if twett in open('palavras.txt','r').read():
print("the word is alrealy in the txt")
else:
wf = open('palavras.txt','a')
wf.write(f"{twett}\n")
wf.close()
推荐阅读
- performance - 什么是深度学习领域的 FLOPS?
- node.js - 在节点应用程序中使用 moment.Js 进行日期格式化
- selenium - 开发人员工具无法使用 Xpath 找到元素,但 Xpath 帮助程序扩展可以
- xpath - Xpath:返回符合任一条件的所有节点
- javascript - 如何从 JSON 对象中删除键下的所有内容
- javascript - 有没有办法让 div 扩展以覆盖所有可用空间,隐藏它扩展的所有内容?
- tensorflow - 移动设备上的视频分割
- javascript - AssertionError [ERR_ASSERTION]: 任务函数必须指定 GULP (node js, keystone js)
- vue.js - Communication between chain vuejs components
- android - 如何修复错误“NoSuchMethodError:getter 'focusScopeNode' was called on null”?