【问题标题】:Python Script - Not Iterating - Loop - STUCKPython 脚本 - 不迭代 - 循环 - 卡住
【发布时间】:2017-05-28 09:40:48
【问题描述】:

遗憾的是,我对 python 知之甚少,有人帮我编写脚本。

我需要将 xyz 文件中的 O(指氧气)更改为 Ob(氧气体积)或 Ow(氧气水)。

在定义.txt 文件中:

1-258
259-795

1-258 - 这指的是前 1-258 个原子,如果这些文件中有一个 O,那么它应该是 Ob 259-795 指的是259-795个原子,如果这些文件中有O,那么应该是Ow

  • 唯一的问题是这需要进行 30000 次迭代
  • 我不断收到此错误

    回溯(最近一次通话最后一次):
    test.py,第 47 行,在 natoms= int(xyz[0].split()[0]) ValueError: int() 以 10 为底的无效文字:'1-258'

  • 任何关于如何解决这个问题的建议将不胜感激!!!

脚本:

*!/usr/bin/env python*

import numpy as np
from sys import argv,exit
from itertools import chain
from math import sqrt
from collections import defaultdict

def get_coordinates(coordinates):
x = float(coordinates.split()[1])
y = float(coordinates.split()[2])
z = float(coordinates.split()[3])
return x,y,z

*Calculate distance between 3 (x,y,z) points*

def vector_distance((x1,y1,z1,x2,y2,z2)):
dist = sqrt((x2 - x1)**2 + (y2 - y1)**2 + (z2-z1)**2)
return dist

def group_to_range(group):
group = ''.join(group.split())
sign, g = ('-', group[1:]) if group.startswith('-') else ('', group)
r = g.split('-', 1)
r[0] = sign + r[0]
r = sorted(int(__) for __ in r)
return range(r[0], 1 + r[-1])

*Expand and sort the list of numbers*

def rangeexpand(txt):
ranges = chain.from_iterable(group_to_range(__) for __ in txt.split(','))
return sorted(set(ranges))
return range(r[0], 1 + r[-1])

*Expand and sort the list of numbers
def rangeexpand(txt):
ranges = chain.from_iterable(group_to_range(__) for __ in txt.split(','))
return sorted(set(ranges))
Usage
create 'defnitions.txt in your directory and add the atom numbers of the
bulk oxygens on the first line and the water oxygens on the second line
e.g
1-45,56,58
46-55,57,59-60*

xyz = open(argv[1],'r').read().splitlines()

definitions=open("definitions.txt",'r').read().splitlines()

bulk=rangeexpand(definitions[0])

water=rangeexpand(definitions[1])

natoms= int(xyz[0].split()[0])

ntrajs=len(xyz)/(natoms+2)

fout=open(argv[1]+"_edited","w")

for i,j in enumerate(xyz):

    if int(j.split()[0])==natoms:

            fout.write("{0}\n".format(j))

            fout.write("{0}\n".format(xyz[i+1]))

    if i+1 in bulk:

            fout.write("{0}-B {1} {2} {3}".format(j.split()[0],j.split()

[1],j.split()[2],j.split()[3]))

    if i+1 in water:

            fout.write("{0}-W {1} {2} {3}".format(j.split()[0],j.split()

[1],j.split()[2],j.split()[3]))

【问题讨论】:

  • 您必须更正格式。 Python 需要缩进和您忽略的特定编码样式。这个例子难以辨认。

标签: python loops iteration


【解决方案1】:

str.split 的默认行为是按空格分割。如果您想用另一个字符/字符串(在您的情况下为'-')拆分,则需要在调用该方法时显式提供它作为参数。

【讨论】:

  • 感谢您的快速回复。请问您能建议需要指定什么来拆分吗?
  • @user.17 我在帖子里告诉过你。
  • 对不起,我是一个新手,不知道如何解决这个问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-05-16
  • 2017-11-15
  • 1970-01-01
  • 2016-08-06
  • 1970-01-01
相关资源
最近更新 更多