Как я могу решить проблему недопустимого литерала для int() с базой 10?Python

Программы на Python
Ответить
Anonymous
 Как я могу решить проблему недопустимого литерала для int() с базой 10?

Сообщение Anonymous »

Следующий код должен выполнять следующие действия: он должен импортировать данные из файла Excel и строить расписание буровой установки на основе диаграммы Ганта. Однако он возвращает следующую ошибку:
Processing command: Add Well A Development in Field X with a spud date of 2024-01-01, duration of 30 days
Parts of the command: ['Add', 'Well', 'A', 'Development', 'in', 'Field', 'X', 'with', 'a', 'spud', 'date', 'of', '2024-01-01,', 'duration', 'of', '30', 'days']
Parsed Spud Date: NaT
Raw duration string: of
Cleaned duration string:
Error processing duration: invalid literal for int() with base 10: ''

import pandas as pd
import plotly.graph_objects as go

# Sample DataFrame to hold well data
schedule = pd.DataFrame(columns=["Well Name", "Well Type", "Field Name", "Spud Date", "Duration", "End Date"])

# Function to process user commands
def process_command(command, schedule, instruction_log):
try:
instruction_log.append(command)

# Print command to debug
print(f"Processing command: {command}")

# Parse "Add" command
if "Add" in command:
parts = command.split(" ")
print(f"Parts of the command: {parts}") # Debugging output

if len(parts) >= 16: # Ensure that we have all parts to parse
well_name = parts[1]
well_type = parts[2]
field_name = parts[4]

# Try to extract and clean the spud date for conversion
spud_date_str = parts[8].replace(",", "") # Remove any commas
try:
spud_date = pd.to_datetime(spud_date_str, errors='coerce')
print(f"Parsed Spud Date: {spud_date}")
except Exception as e:
print(f"Error parsing spud date: {e}")
return schedule # Return unmodified schedule on error

# Extract and clean the duration
try:
# Duration typically follows "duration of"
duration_str = parts[11] # Duration is often the 11th part
print(f"Raw duration string: {duration_str}") # Debugging output

# Clean the string: remove 'of', 'days' and strip any extra characters like commas
cleaned_duration = duration_str.replace("of", "").replace("days", "").strip(",").strip()
print(f"Cleaned duration string: {cleaned_duration}") # Debugging output

# Try to convert the cleaned string to an integer
duration = int(cleaned_duration)
print(f"Parsed Duration: {duration}") # Debugging output

if not duration: # Check for a valid number
raise ValueError("Invalid duration format.")
except ValueError as e:
print(f"Error processing duration: {e}")
return schedule # Return the unmodified schedule on error

# Add new well to schedule
new_well = {
"Well Name": well_name,
"Well Type": well_type,
"Field Name": field_name,
"Spud Date": spud_date,
"Duration": duration,
"End Date": spud_date + pd.to_timedelta(duration, unit="D"),
}
schedule = schedule.append(new_well, ignore_index=True)
print(f"Updated Schedule:\n{schedule}") # Debugging output

# Parse "Update" command
elif "Update" in command:
parts = command.split(" ")
if len(parts) >= 8: # Ensure we have enough parts to process
well_name = parts[4]
try:
# Look for new duration after "duration" and remove "days"
new_duration_str = parts[7]
new_duration = int(new_duration_str.replace("days", "").strip()) # Clean and convert
schedule.loc[schedule['Well Name'] == well_name, 'Duration'] = new_duration
schedule['End Date'] = schedule['Spud Date'] + pd.to_timedelta(schedule['Duration'], unit="D")
print(f"Updated Schedule after Update:\n{schedule}") # Debugging output
except ValueError:
print("Error processing duration in the Update command.")
return schedule # Return the unmodified schedule on error

# Generate Gantt Chart based on the updated schedule
return generate_gantt_chart(schedule)

except Exception as e:
print(f"Error processing command: {e}")
return schedule # Return the unmodified schedule on error

# Function to generate the Gantt chart
def generate_gantt_chart(schedule):
# Check if the schedule DataFrame is empty
if schedule.empty:
print("No data available for Gantt chart.")
return None

# Create color mapping based on Well Type
color_map = {
'Development': 'darkred',
'Injector': 'orange',
'Appraisal': 'green',
'Exploration': 'yellow',
'Water supply': 'lightblue',
'Water Disposal': 'lightblue'
}

# Create the Gantt chart
fig = go.Figure()

for _, row in schedule.iterrows():
well_type = row['Well Type']
color = color_map.get(well_type, 'gray') # Default color if not found in the map

fig.add_trace(go.Bar(
x=[row['End Date'] - row['Spud Date']],
y=[row['Well Name']],
base=row['Spud Date'],
orientation='h',
marker=dict(color=color),
name=row['Well Name']
))

# Update the layout for Gantt chart styling
fig.update_layout(
barmode='stack',
title='Drilling Schedule',
xaxis_title='Date',
yaxis_title='Well Name',
xaxis=dict(tickformat="%Y-%m-%d"),
showlegend=False
)

# Show the plot
fig.show()

# Example Commands
schedule = process_command("Add Well A Development in Field X with a spud date of 2024-01-01, duration of 30 days", schedule, [])
schedule = process_command("Add Well B Injector in Field X with a spud date of 2024-02-01, duration of 45 days", schedule, [])


Подробнее здесь: https://stackoverflow.com/questions/792 ... th-base-10
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «Python»