Вы можете попробовать что-то вроде
String str = "UPUPLEFTRIGHTUP";
int countUP = ( str.split("UP", -1).length ) - 1;
int countLEFT = ( str.split("LEFT", -1).length ) - 1;
int countRIGHT = ( str.split("RIGHT", -1).length ) - 1;
int countDOWN = ( str.split("DOWN", -1).length ) - 1;
Ограничение можно проверить, сравнив значения int
с пределами поля (10*10
в вашем случае).
Для позиции, если предположить, что каждое движение составляет 1 единицу, то:
int x = 0; //starting point in Ox axis
int y = 0; //starting point in Oy axis
x = countRIGHT - CountLeft;
y = countUP - CountDOWN;
Пара (x,y)
- это позиция вашего робота.
int[] walk(String path) {
int[] position = {0,0};
int countUP = ( path.split("UP", -1).length ) - 1; //Counts how many UP command
int countLEFT = ( path.split("LEFT", -1).length ) - 1; //Counts how many LEFT command
int countRIGHT = ( path.split("RIGHT", -1).length ) - 1; //Counts how many RIGHT command
int countDOWN = ( path.split("DOWN", -1).length ) - 1; //Counts how many DOWN command
position[0] = countRIGHT - countLEFT;
position[1] = countUP - countDown;
return position;
}
Это не тот код, который вам нужен, а просто демонстрация того, как работать с BeautifulSoup. Он находит таблицу с идентификатором "Table1" и получает все ее элементы tr.
html = urllib2.urlopen(url).read()
bs = BeautifulSoup(html)
table = bs.find(lambda tag: tag.name=='table' and tag.has_attr('id') and tag['id']=="Table1")
rows = table.findAll(lambda tag: tag.name=='tr')
Если вам интересно, BeautifulSoup больше не поддерживается, и первоначальный сопровождающий предлагает перейти на lxml. Xpath должен отлично справиться с задачей.
Здесь работает пример на дженерик <table>
. (Не используя Вашу страницу должное выполнение JavaScript должно было загрузить данные таблицы)
Извлечение данных таблицы от [1 111] здесь GDP (Валовой внутренний продукт) странами.
table = soup.find('table', { 'class' : 'table table-striped' })
# where the dictionary specify unique attributes for the 'table' tag
Bellow основное tableDataText
функция анализирует сегмент HTML, запущенный с тега <table>
сопровождаемый приблизительно <tr>
(строки таблицы) и внутренний <td>
(данные таблицы) теги. Это возвращает список строк с внутренними столбцами. Принимает только один <th>
(таблица, header/data) в первой строке.
def rowgetDataText(tr, coltag='td'): # td (data) or th (header)
cols = []
for td in tr.find_all(coltag):
cols.append(td.get_text(strip=True))
return cols
def tableDataText(table):
rows = []
trs = table.find_all('tr')
headerow = rowgetDataText(trs[0], 'th')
if headerow: # if there is a header row include first
rows.append(headerow)
trs = trs[1:]
for tr in trs: # for every table row
rows.append(rowgetDataText(tr, 'td')) # data row
return rows
Используя его мы добираемся (сначала две строки).
list_table = tableDataText(htmltable)
list_table[:2]
[['Rank',
'Name',
"GDP (IMF '19)",
"GDP (UN '16)",
'GDP Per Capita',
'2019 Population'],
['1',
'United States',
'21.41 trillion',
'18.62 trillion',
'$65,064',
'329,064,917']]
, Который может быть легко преобразован в pandas.DataFrame
для более усовершенствованного управления.
import pandas as pd
dftable = pd.DataFrame(list_table[1:], columns=list_table[0])
dftable.head(4)
soup = BeautifulSoup(HTML)
# the first argument to find tells it what tag to search for
# the second you can pass a dict of attr->value pairs to filter
# results that match the first tag
table = soup.find( "table", {"title":"TheTitle"} )
rows=list()
for row in table.findAll("tr"):
rows.append(row)
# now rows contains each tr in the table (as a BeautifulSoup object)
# and you can search them to pull out the times