网络药理学:SwissADME和PubChem和TCMSP互通(TCMSP爬虫批量得到化合物名称或Mol ID、批量转换为SDF文件/SMILES序列号/CID)

TCMSP爬虫批量得到化合物名称或Mol ID

见我的另一篇博客:http://t.csdnimg.cn/lTg6k

通过化合物名称批量获得SMILES序列号/CID序列号

import pubchempy
import pandas as pd
import itertools
import time

def read_file(file_name) -> list:
    """
    读取化合物名称
    :param file_name: 含有化合物名称的txt或csv格式文件(含路径)
    :return: list
    """
    try:
        df = pd.read_csv(file_name, sep=',', encoding='utf-8-sig')
        if 'Molecule Name' in df.columns.values:
            return df['Molecule Name'].tolist()
    except pd.errors.ParserError:  # 如果文件不是CSV格式,说明是txt格式,继续尝试
        pass

    with open(file_name, 'r', encoding='utf-8-sig') as file:
        return [line.strip() for line in file.readlines()]


def get_compound_info(name: list):
    """
    获取化合物信息
    :param name: 化合物名称列表
    """
    try:
        compounds = pubchempy.get_compounds(name, 'name')
        for compound in compounds:
            result = {
                'name': name,
                'molecular_formula': compound.molecular_formula,
                'molecular_weight': compound.molecular_weight,
                'smiles': compound.isomeric_smiles,
                'synonyms': compound.synonyms,
                'cid': compound.cid
            }
            print(
                f"CID: {compound.cid}\tMass: {compound.exact_mass}\tName: {compound.iupac_name}\tMolfor: {compound.molecular_formula}\tSmi: {compound.isomeric_smiles}\tSyn: {compound.synonyms}")
            yield result
    except Exception as e:
        print("occurred error when processing compound", name)
        print(str(e))
        return


def chemName_to_Smiles_or_CID(input_file_name, output_file_name):
    """
    通过化合物名称批量获得SMILES序列号/CID序列号
    :param input_file_name:含有化合物名称的txt格式文件(含路径),一行一个化合物名称,换行符分隔
    :param output_file_name: 输出文件(含路径)
    """

    start_time = time.time()

    # 输入
    name_list = read_file(input_file_name)
    # 生成器优化循环遍历
    results = itertools.chain.from_iterable(get_compound_info(name) for name in name_list)
    # 输出
    dataframe = pd.DataFrame(results)
    dataframe.to_csv(output_file_name, index=False, sep=',')
    
    # 结束计时
    end_time = time.time()
    print(f"Total queries: {len(dataframe)}")
    print(f"Elapsed time: {end_time - start_time:.2f} seconds")


if __name__ == '__main__':
    print("start convert")

    input_file_name = "1-TCMSP.csv"
    output_file_name = "smiles_and_cid.csv"

    chemName_to_Smiles_or_CID(input_file_name, output_file_name)

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
首先需要了解得物网站的数据结构和爬取方式,得物网站比较复杂,需要使用Selenium+BeautifulSoup进行爬取。 以下是一个简单的得物爬虫Python代码实现(注:仅供学习参考,请勿用于商业用途): ```python import time from selenium import webdriver from selenium.webdriver.chrome.options import Options from bs4 import BeautifulSoup options = Options() options.add_argument('--no-sandbox') # 解决DevToolsActivePort文件不存在报错的问题 options.add_argument('window-size=1920x3000') # 指定浏览器分辨率 options.add_argument('--disable-gpu') # 谷歌文档提到需要加上这个属性来规避bug options.add_argument('--hide-scrollbars') # 隐藏滚动条, 应对一些特殊页面 options.add_argument('blink-settings=imagesEnabled=false') # 不加载图片, 提升速度 options.add_argument('--headless') # 无界面 driver = webdriver.Chrome(options=options) url = 'https://www.dewu.com/' driver.get(url) # 等待页面加载完成 time.sleep(3) # 模拟鼠标点击,展开商品列表 driver.find_element_by_xpath('//div[text()="全部商品"]').click() # 等待页面加载完成 time.sleep(3) # 获取页面源代码 html = driver.page_source # 解析页面 soup = BeautifulSoup(html, 'html.parser') # 获取商品列表 items = soup.find_all('div', {'class': 'item-card'}) for item in items: # 获取商品标题 title = item.find('div', {'class': 'title'}).text.strip() # 获取商品价格 price = item.find('div', {'class': 'price'}).text.strip() # 获取商品链接 link = item.find('a', {'class': 'item-link'})['href'] print(title, price, link) # 关闭浏览器 driver.quit() ``` 这里的代码仅仅是一个简单的爬虫示例,如果想要更加深入地了解得物网站的数据结构和爬取方式,需要结合具体的需求进行更加详细的分析和实现。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

鸡鸭扣

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值